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/QTcpSocket>
50 #include <QtCore/QByteArray>
51 #include <QtCore/QtEndian>
52 #include <QtCore/QCryptographicHash>
53 #include <QtCore/QRegularExpression>
54 #include <QtCore/QStringList>
55 #include <QtNetwork/QHostAddress>
56 #include <QtCore/QStringBuilder> //for more efficient string concatenation
57 #ifndef QT_NONETWORKPROXY
58 #include <QtNetwork/QNetworkProxy>
61 #include <QtNetwork/QSslConfiguration>
62 #include <QtNetwork/QSslError>
65 #include <QtCore/QDebug>
71 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2; //maximum size of a frame when sending a message
73 QWebSocketConfiguration::QWebSocketConfiguration() :
75 m_sslConfiguration(QSslConfiguration::defaultConfiguration()),
77 m_ignoreSslErrors(false),
79 #ifndef QT_NONETWORKPROXY
80 m_proxy(QNetworkProxy::DefaultProxy)
88 QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version, QWebSocket *pWebSocket, QObject *parent) :
99 m_socketState(QAbstractSocket::UnconnectedState),
102 m_isClosingHandshakeSent(false),
103 m_isClosingHandshakeReceived(false),
108 Q_ASSERT(pWebSocket);
109 qsrand(static_cast<uint>(QDateTime::currentMSecsSinceEpoch()));
115 QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version, QWebSocket *pWebSocket, QObject *parent) :
118 m_pSocket(pTcpSocket),
119 m_errorString(pTcpSocket->errorString()),
126 m_socketState(pTcpSocket->state()),
129 m_isClosingHandshakeSent(false),
130 m_isClosingHandshakeReceived(false),
135 Q_ASSERT(pWebSocket);
136 makeConnections(m_pSocket);
142 QWebSocketPrivate::~QWebSocketPrivate()
146 if (state() == QAbstractSocket::ConnectedState)
148 close(QWebSocketProtocol::CC_GOING_AWAY, tr("Connection closed"));
150 releaseConnections(m_pSocket);
151 m_pSocket->deleteLater();
152 m_pSocket = Q_NULLPTR;
159 void QWebSocketPrivate::abort()
170 QAbstractSocket::SocketError QWebSocketPrivate::error() const
172 QAbstractSocket::SocketError err = QAbstractSocket::OperationError;
175 err = m_pSocket->error();
183 QString QWebSocketPrivate::errorString() const
186 if (!m_errorString.isEmpty())
188 errMsg = m_errorString;
192 errMsg = m_pSocket->errorString();
200 bool QWebSocketPrivate::flush()
205 result = m_pSocket->flush();
213 qint64 QWebSocketPrivate::write(const char *message)
215 //TODO: create a QByteArray from message, and directly call doWriteData
216 //now the data is converted to a string, and then converted back to a bytearray
217 return write(QString::fromUtf8(message));
223 qint64 QWebSocketPrivate::write(const char *message, qint64 maxSize)
225 //TODO: create a QByteArray from message, and directly call doWriteData
226 //now the data is converted to a string, and then converted back to a bytearray
227 return write(QString::fromUtf8(message, static_cast<int>(maxSize)));
233 qint64 QWebSocketPrivate::write(const QString &message)
235 return doWriteData(message.toUtf8(), false);
241 qint64 QWebSocketPrivate::write(const QByteArray &data)
243 return doWriteData(data, true);
250 void QWebSocketPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
252 m_configuration.m_sslConfiguration = sslConfiguration;
258 QSslConfiguration QWebSocketPrivate::sslConfiguration() const
260 return m_configuration.m_sslConfiguration;
266 void QWebSocketPrivate::ignoreSslErrors(const QList<QSslError> &errors)
268 m_configuration.m_ignoredSslErrors = errors;
274 void QWebSocketPrivate::ignoreSslErrors()
276 m_configuration.m_ignoreSslErrors = true;
279 QSslSocket *pSslSocket = qobject_cast<QSslSocket *>(m_pSocket);
282 pSslSocket->ignoreSslErrors();
290 Called from QWebSocketServer
293 QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
294 const QWebSocketHandshakeRequest &request,
295 const QWebSocketHandshakeResponse &response,
298 QWebSocket *pWebSocket = new QWebSocket(pTcpSocket, response.acceptedVersion(), parent);
299 pWebSocket->d_func()->setExtension(response.acceptedExtension());
300 pWebSocket->d_func()->setOrigin(request.origin());
301 pWebSocket->d_func()->setRequestUrl(request.requestUrl());
302 pWebSocket->d_func()->setProtocol(response.acceptedProtocol());
303 pWebSocket->d_func()->setResourceName(request.requestUrl().toString(QUrl::RemoveUserInfo));
304 //a server should not send masked frames
305 pWebSocket->d_func()->enableMasking(false);
313 void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
317 if (!m_isClosingHandshakeSent)
320 quint32 maskingKey = 0;
323 maskingKey = generateMaskingKey();
325 const quint16 code = qToBigEndian<quint16>(closeCode);
327 payload.append(static_cast<const char *>(static_cast<const void *>(&code)), 2);
328 if (!reason.isEmpty())
330 payload.append(reason.toUtf8());
334 QWebSocketProtocol::mask(payload.data(), payload.size(), maskingKey);
336 QByteArray frame = getFrameHeader(QWebSocketProtocol::OC_CLOSE, payload.size(), maskingKey, true);
337 frame.append(payload);
338 m_pSocket->write(frame);
341 m_isClosingHandshakeSent = true;
343 Q_EMIT q->aboutToClose();
352 void QWebSocketPrivate::open(const QUrl &url, bool mask)
358 m_dataProcessor.clear();
359 m_isClosingHandshakeReceived = false;
360 m_isClosingHandshakeSent = false;
363 QString resourceName = url.path();
364 if (!url.query().isEmpty())
366 if (!resourceName.endsWith(QChar::fromLatin1('?')))
368 resourceName.append(QChar::fromLatin1('?'));
370 resourceName.append(url.query());
372 if (resourceName.isEmpty())
374 resourceName = QStringLiteral("/");
376 setResourceName(resourceName);
380 if (url.scheme() == QStringLiteral("wss"))
382 if (!QSslSocket::supportsSsl())
384 const QString message = tr("SSL Sockets are not supported on this platform.");
385 qWarning() << message;
386 setErrorString(message);
387 emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
391 QSslSocket *sslSocket = new QSslSocket(this);
392 m_pSocket = sslSocket;
394 makeConnections(m_pSocket);
395 connect(sslSocket, SIGNAL(encryptedBytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
396 setSocketState(QAbstractSocket::ConnectingState);
398 sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
399 if (m_configuration.m_ignoreSslErrors)
401 sslSocket->ignoreSslErrors();
405 sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
407 #ifndef QT_NO_NETWORKPROXY
408 sslSocket->setProxy(m_configuration.m_proxy);
410 sslSocket->connectToHostEncrypted(url.host(), url.port(443));
415 if (url.scheme() == QStringLiteral("ws"))
417 m_pSocket = new QTcpSocket(this);
419 makeConnections(m_pSocket);
420 connect(m_pSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
421 setSocketState(QAbstractSocket::ConnectingState);
422 #ifndef QT_NO_NETWORKPROXY
423 m_pSocket->setProxy(m_configuration.m_proxy);
425 m_pSocket->connectToHost(url.host(), url.port(80));
429 const QString message = tr("Unsupported websockets scheme: %1").arg(url.scheme());
430 qWarning() << message;
431 setErrorString(message);
432 emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
440 void QWebSocketPrivate::ping(const QByteArray &payload)
442 Q_ASSERT(payload.length() < 126);
443 m_pingTimer.restart();
444 QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OC_PING, payload.size(), 0 /*do not mask*/, true);
445 pingFrame.append(payload);
446 writeFrame(pingFrame);
451 Sets the version to use for the websocket protocol; this must be set before the socket is opened.
453 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
460 Sets the resource name of the connection; must be set before the socket is openend
462 void QWebSocketPrivate::setResourceName(const QString &resourceName)
464 m_resourceName = resourceName;
470 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
472 m_requestUrl = requestUrl;
478 void QWebSocketPrivate::setOrigin(const QString &origin)
486 void QWebSocketPrivate::setProtocol(const QString &protocol)
488 m_protocol = protocol;
494 void QWebSocketPrivate::setExtension(const QString &extension)
496 m_extension = extension;
502 void QWebSocketPrivate::enableMasking(bool enable)
510 qint64 QWebSocketPrivate::doWriteData(const QByteArray &data, bool isBinary)
512 return doWriteFrames(data, isBinary);
518 void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
520 Q_ASSERT(pTcpSocket);
523 //pass through signals
524 connect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SIGNAL(error(QAbstractSocket::SocketError)));
525 connect(pTcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), q, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
526 connect(pTcpSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
527 connect(pTcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
528 //connect(pTcpSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
531 connect(pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processStateChanged(QAbstractSocket::SocketState)));
532 connect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(processData()));
534 connect(&m_dataProcessor, SIGNAL(textFrameReceived(QString,bool)), q, SIGNAL(textFrameReceived(QString,bool)));
535 connect(&m_dataProcessor, SIGNAL(binaryFrameReceived(QByteArray,bool)), q, SIGNAL(binaryFrameReceived(QByteArray,bool)));
536 connect(&m_dataProcessor, SIGNAL(binaryMessageReceived(QByteArray)), q, SIGNAL(binaryMessageReceived(QByteArray)));
537 connect(&m_dataProcessor, SIGNAL(textMessageReceived(QString)), q, SIGNAL(textMessageReceived(QString)));
538 connect(&m_dataProcessor, SIGNAL(errorEncountered(QWebSocketProtocol::CloseCode,QString)), this, SLOT(close(QWebSocketProtocol::CloseCode,QString)));
539 connect(&m_dataProcessor, SIGNAL(pingReceived(QByteArray)), this, SLOT(processPing(QByteArray)));
540 connect(&m_dataProcessor, SIGNAL(pongReceived(QByteArray)), this, SLOT(processPong(QByteArray)));
541 connect(&m_dataProcessor, SIGNAL(closeReceived(QWebSocketProtocol::CloseCode,QString)), this, SLOT(processClose(QWebSocketProtocol::CloseCode,QString)));
547 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
552 //pass through signals
553 disconnect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SIGNAL(error(QAbstractSocket::SocketError)));
554 disconnect(pTcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), q, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
555 disconnect(pTcpSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
556 disconnect(pTcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
557 //disconnect(pTcpSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
560 disconnect(pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processStateChanged(QAbstractSocket::SocketState)));
561 disconnect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(processData()));
563 disconnect(&m_dataProcessor, SIGNAL(pingReceived(QByteArray)), this, SLOT(processPing(QByteArray)));
564 disconnect(&m_dataProcessor, SIGNAL(pongReceived(QByteArray)), this, SLOT(processPong(QByteArray)));
565 disconnect(&m_dataProcessor, SIGNAL(closeReceived(QWebSocketProtocol::CloseCode,QString)), this, SLOT(processClose(QWebSocketProtocol::CloseCode,QString)));
566 disconnect(&m_dataProcessor, SIGNAL(textFrameReceived(QString,bool)), q, SIGNAL(textFrameReceived(QString,bool)));
567 disconnect(&m_dataProcessor, SIGNAL(binaryFrameReceived(QByteArray,bool)), q, SIGNAL(binaryFrameReceived(QByteArray,bool)));
568 disconnect(&m_dataProcessor, SIGNAL(binaryMessageReceived(QByteArray)), q, SIGNAL(binaryMessageReceived(QByteArray)));
569 disconnect(&m_dataProcessor, SIGNAL(textMessageReceived(QString)), q, SIGNAL(textMessageReceived(QString)));
570 disconnect(&m_dataProcessor, SIGNAL(errorEncountered(QWebSocketProtocol::CloseCode,QString)), this, SLOT(close(QWebSocketProtocol::CloseCode,QString)));
576 QWebSocketProtocol::Version QWebSocketPrivate::version() const
584 QString QWebSocketPrivate::resourceName() const
586 return m_resourceName;
592 QUrl QWebSocketPrivate::requestUrl() const
600 QString QWebSocketPrivate::origin() const
608 QString QWebSocketPrivate::protocol() const
616 QString QWebSocketPrivate::extension() const
624 QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode, quint64 payloadLength, quint32 maskingKey, bool lastFrame) const
628 bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
632 //FIN, RSV1-3, opcode
633 byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00)); //FIN, opcode
634 //RSV-1, RSV-2 and RSV-3 are zero
635 header.append(static_cast<char>(byte));
637 //Now write the masking bit and the payload length byte
643 if (payloadLength <= 125)
645 byte |= static_cast<quint8>(payloadLength);
646 header.append(static_cast<char>(byte));
648 else if (payloadLength <= 0xFFFFU)
651 header.append(static_cast<char>(byte));
652 quint16 swapped = qToBigEndian<quint16>(static_cast<quint16>(payloadLength));
653 header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 2);
655 else if (payloadLength <= 0x7FFFFFFFFFFFFFFFULL)
658 header.append(static_cast<char>(byte));
659 quint64 swapped = qToBigEndian<quint64>(payloadLength);
660 header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 8);
666 //TODO: to big endian?
667 const quint32 mask = qToBigEndian<quint32>(maskingKey);
668 header.append(static_cast<const char *>(static_cast<const void *>(&mask)), sizeof(quint32));
673 //setErrorString("WebSocket::getHeader: payload too big!");
674 //Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
675 qDebug() << "WebSocket::getHeader: payload too big!";
684 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
686 qint64 payloadWritten = 0;
690 const QWebSocketProtocol::OpCode firstOpCode = isBinary ? QWebSocketProtocol::OC_BINARY : QWebSocketProtocol::OC_TEXT;
692 int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
693 QByteArray tmpData(data);
695 char *payload = tmpData.data();
696 quint64 sizeLeft = static_cast<quint64>(data.size()) % FRAME_SIZE_IN_BYTES;
701 if (numFrames == 0) //catch the case where the payload is zero bytes; in that case, we still need to send a frame
705 quint64 currentPosition = 0;
706 qint64 bytesWritten = 0;
707 quint64 bytesLeft = data.size();
709 for (int i = 0; i < numFrames; ++i)
711 quint32 maskingKey = 0;
714 maskingKey = generateMaskingKey();
717 const bool isLastFrame = (i == (numFrames - 1));
718 const bool isFirstFrame = (i == 0);
720 const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
721 const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode : QWebSocketProtocol::OC_CONTINUE;
724 bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
729 char *currentData = payload + currentPosition;
732 QWebSocketProtocol::mask(currentData, size, maskingKey);
734 qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
737 bytesWritten += written;
738 payloadWritten += written;
742 setErrorString(tr("Error writing bytes to socket: %1.").arg(m_pSocket->errorString()));
743 qDebug() << errorString();
745 Q_EMIT q->error(QAbstractSocket::NetworkError);
749 currentPosition += size;
752 if (payloadWritten != data.size())
754 setErrorString(tr("Bytes written %1 != %2.").arg(payloadWritten).arg(data.size()));
755 qDebug() << errorString();
756 Q_EMIT q->error(QAbstractSocket::NetworkError);
759 return payloadWritten;
765 quint32 QWebSocketPrivate::generateRandomNumber() const
767 return static_cast<quint32>((static_cast<double>(qrand()) / RAND_MAX) * std::numeric_limits<quint32>::max());
773 quint32 QWebSocketPrivate::generateMaskingKey() const
775 return generateRandomNumber();
781 QByteArray QWebSocketPrivate::generateKey() const
785 for (int i = 0; i < 4; ++i)
787 quint32 tmp = generateRandomNumber();
788 key.append(static_cast<const char *>(static_cast<const void *>(&tmp)), sizeof(quint32));
791 return key.toBase64();
798 QString QWebSocketPrivate::calculateAcceptKey(const QString &key) const
800 const QString tmpKey = key % QStringLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
801 const QByteArray hash = QCryptographicHash::hash(tmpKey.toLatin1(), QCryptographicHash::Sha1);
802 return QString::fromLatin1(hash.toBase64());
808 qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
813 for (int i = 0; i < frames.size(); ++i)
815 written += writeFrame(frames[i]);
824 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
829 written = m_pSocket->write(frame);
837 QString readLine(QTcpSocket *pSocket)
844 while (pSocket->getChar(&c))
848 pSocket->getChar(&c);
853 line.append(QChar::fromLatin1(c));
860 //called on the client for a server handshake response
864 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
873 QString errorDescription;
875 const QString regExpStatusLine(QStringLiteral("^(HTTP/[0-9]+\\.[0-9]+)\\s([0-9]+)\\s(.*)"));
876 const QRegularExpression regExp(regExpStatusLine);
877 const QString statusLine = readLine(pSocket);
878 QString httpProtocol;
880 QString httpStatusMessage;
881 const QRegularExpressionMatch match = regExp.match(statusLine);
882 if (match.hasMatch())
884 QStringList tokens = match.capturedTexts();
885 tokens.removeFirst(); //remove the search string
886 if (tokens.length() == 3)
888 httpProtocol = tokens[0];
889 httpStatusCode = tokens[1].toInt();
890 httpStatusMessage = tokens[2].trimmed();
896 errorDescription = tr("Invalid statusline in response: %1.").arg(statusLine);
900 QString headerLine = readLine(pSocket);
901 QMap<QString, QString> headers;
902 while (!headerLine.isEmpty())
904 const QStringList headerField = headerLine.split(QStringLiteral(": "), QString::SkipEmptyParts);
905 headers.insertMulti(headerField[0], headerField[1]);
906 headerLine = readLine(pSocket);
909 const QString acceptKey = headers.value(QStringLiteral("Sec-WebSocket-Accept"), QStringLiteral(""));
910 const QString upgrade = headers.value(QStringLiteral("Upgrade"), QStringLiteral(""));
911 const QString connection = headers.value(QStringLiteral("Connection"), QStringLiteral(""));
912 //unused for the moment
913 //const QString extensions = headers.value(QStringLiteral("Sec-WebSocket-Extensions"), QStringLiteral(""));
914 //const QString protocol = headers.value(QStringLiteral("Sec-WebSocket-Protocol"), QStringLiteral(""));
915 const QString version = headers.value(QStringLiteral("Sec-WebSocket-Version"), QStringLiteral(""));
917 if (httpStatusCode == 101) //HTTP/x.y 101 Switching Protocols
919 bool conversionOk = false;
920 const float version = httpProtocol.midRef(5).toFloat(&conversionOk);
921 //TODO: do not check the httpStatusText right now
922 ok = !(acceptKey.isEmpty() ||
923 (!conversionOk || (version < 1.1f)) ||
924 (upgrade.toLower() != QStringLiteral("websocket")) ||
925 (connection.toLower() != QStringLiteral("upgrade")));
928 const QString accept = calculateAcceptKey(QString::fromLatin1(m_key));
929 ok = (accept == acceptKey);
932 errorDescription = tr("Accept-Key received from server %1 does not match the client key %2.").arg(acceptKey).arg(accept);
937 errorDescription = tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.").arg(statusLine);
940 else if (httpStatusCode == 400) //HTTP/1.1 400 Bad Request
942 if (!version.isEmpty())
944 const QStringList versions = version.split(QStringLiteral(", "), QString::SkipEmptyParts);
945 if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion())))
947 //if needed to switch protocol version, then we are finished here
948 //because we cannot handle other protocols than the RFC one (v13)
949 errorDescription = tr("Handshake: Server requests a version that we don't support: %1.").arg(versions.join(QStringLiteral(", ")));
954 //we tried v13, but something different went wrong
955 errorDescription = tr("QWebSocketPrivate::processHandshake: Unknown error condition encountered. Aborting connection.");
962 errorDescription = tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).").arg(httpStatusCode).arg(httpStatusMessage);
968 qDebug() << errorDescription;
969 setErrorString(errorDescription);
970 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
974 //handshake succeeded
975 setSocketState(QAbstractSocket::ConnectedState);
976 Q_EMIT q->connected();
984 void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState)
988 QAbstractSocket::SocketState webSocketState = this->state();
991 case QAbstractSocket::ConnectedState:
993 if (webSocketState == QAbstractSocket::ConnectingState)
995 m_key = generateKey();
996 QString handshake = createHandShakeRequest(m_resourceName, m_requestUrl.host() % QStringLiteral(":") % QString::number(m_requestUrl.port(80)), origin(), QStringLiteral(""), QStringLiteral(""), m_key);
997 m_pSocket->write(handshake.toLatin1());
1001 case QAbstractSocket::ClosingState:
1003 if (webSocketState == QAbstractSocket::ConnectedState)
1005 setSocketState(QAbstractSocket::ClosingState);
1009 case QAbstractSocket::UnconnectedState:
1011 if (webSocketState != QAbstractSocket::UnconnectedState)
1013 setSocketState(QAbstractSocket::UnconnectedState);
1014 Q_EMIT q->disconnected();
1018 case QAbstractSocket::HostLookupState:
1019 case QAbstractSocket::ConnectingState:
1020 case QAbstractSocket::BoundState:
1021 case QAbstractSocket::ListeningState:
1024 //to make C++ compiler happy;
1035 //connectToHost is called
1036 //our socket state is set to "connecting", and tcpSocket->connectToHost is called
1037 //the tcpsocket is opened, a handshake message is sent; a readyRead signal is thrown
1038 //this signal is catched by processData
1039 //when OUR socket state is in the "connecting state", this means that
1040 //we have received data from the server (response to handshake), and that we
1041 //should "upgrade" our socket to a websocket (connected state)
1042 //if our socket was already upgraded, then we need to process websocket data
1046 void QWebSocketPrivate::processData()
1048 Q_ASSERT(m_pSocket);
1049 while (m_pSocket->bytesAvailable())
1051 if (state() == QAbstractSocket::ConnectingState)
1053 processHandshake(m_pSocket);
1057 m_dataProcessor.process(m_pSocket);
1065 void QWebSocketPrivate::processPing(QByteArray data)
1067 Q_ASSERT(m_pSocket);
1068 quint32 maskingKey = 0;
1071 maskingKey = generateMaskingKey();
1073 m_pSocket->write(getFrameHeader(QWebSocketProtocol::OC_PONG, data.size(), maskingKey, true));
1074 if (data.size() > 0)
1078 QWebSocketProtocol::mask(&data, maskingKey);
1080 m_pSocket->write(data);
1087 void QWebSocketPrivate::processPong(QByteArray data)
1090 Q_EMIT q->pong(static_cast<quint64>(m_pingTimer.elapsed()), data);
1096 void QWebSocketPrivate::processClose(QWebSocketProtocol::CloseCode closeCode, QString closeReason)
1098 m_isClosingHandshakeReceived = true;
1099 close(closeCode, closeReason);
1105 QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
1112 QStringList handshakeRequest;
1114 handshakeRequest << QStringLiteral("GET ") % resourceName % QStringLiteral(" HTTP/1.1") <<
1115 QStringLiteral("Host: ") % host <<
1116 QStringLiteral("Upgrade: websocket") <<
1117 QStringLiteral("Connection: Upgrade") <<
1118 QStringLiteral("Sec-WebSocket-Key: ") % QString::fromLatin1(key);
1119 if (!origin.isEmpty())
1121 handshakeRequest << QStringLiteral("Origin: ") % origin;
1123 handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ") % QString::number(QWebSocketProtocol::currentVersion());
1124 if (extensions.length() > 0)
1126 handshakeRequest << QStringLiteral("Sec-WebSocket-Extensions: ") % extensions;
1128 if (protocols.length() > 0)
1130 handshakeRequest << QStringLiteral("Sec-WebSocket-Protocol: ") % protocols;
1132 handshakeRequest << QStringLiteral("\r\n");
1134 return handshakeRequest.join(QStringLiteral("\r\n"));
1140 QAbstractSocket::SocketState QWebSocketPrivate::state() const
1142 return m_socketState;
1148 bool QWebSocketPrivate::waitForConnected(int msecs)
1150 bool result = false;
1153 result = m_pSocket->waitForConnected(msecs);
1161 bool QWebSocketPrivate::waitForDisconnected(int msecs)
1163 bool result = false;
1166 result = m_pSocket->waitForDisconnected(msecs);
1174 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
1177 if (m_socketState != state)
1179 m_socketState = state;
1180 Q_EMIT q->stateChanged(m_socketState);
1187 void QWebSocketPrivate::setErrorString(const QString &errorString)
1189 m_errorString = errorString;
1195 QHostAddress QWebSocketPrivate::localAddress() const
1197 QHostAddress address;
1200 address = m_pSocket->localAddress();
1208 quint16 QWebSocketPrivate::localPort() const
1213 port = m_pSocket->localPort();
1221 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
1223 QAbstractSocket::PauseModes mode = QAbstractSocket::PauseNever;
1226 mode = m_pSocket->pauseMode();
1234 QHostAddress QWebSocketPrivate::peerAddress() const
1236 QHostAddress address;
1239 address = m_pSocket->peerAddress();
1247 QString QWebSocketPrivate::peerName() const
1252 name = m_pSocket->peerName();
1260 quint16 QWebSocketPrivate::peerPort() const
1265 port = m_pSocket->peerPort();
1270 #ifndef QT_NO_NETWORKPROXY
1274 QNetworkProxy QWebSocketPrivate::proxy() const
1276 return m_configuration.m_proxy;
1282 void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
1284 m_configuration.m_proxy = networkProxy;
1286 #endif //QT_NO_NETWORKPROXY
1291 qint64 QWebSocketPrivate::readBufferSize() const
1296 size = m_pSocket->readBufferSize();
1304 void QWebSocketPrivate::resume()
1308 m_pSocket->resume();
1315 void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
1319 m_pSocket->setPauseMode(pauseMode);
1326 void QWebSocketPrivate::setReadBufferSize(qint64 size)
1330 m_pSocket->setReadBufferSize(size);
1337 void QWebSocketPrivate::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
1341 m_pSocket->setSocketOption(option, value);
1348 QVariant QWebSocketPrivate::socketOption(QAbstractSocket::SocketOption option)
1353 val = m_pSocket->socketOption(option);
1361 bool QWebSocketPrivate::isValid() const
1363 return (m_pSocket && m_pSocket->isValid());