Connect sslErrors signal when a secure connection is established
[contrib/qtwebsockets.git] / src / websockets / qwebsocket_p.cpp
index 7b7af11..1c4baca 100644 (file)
@@ -46,6 +46,7 @@
 #include "qwebsockethandshakeresponse_p.h"
 
 #include <QtCore/QUrl>
+#include <QtNetwork/QAuthenticator>
 #include <QtNetwork/QTcpSocket>
 #include <QtCore/QByteArray>
 #include <QtCore/QtEndian>
@@ -85,11 +86,12 @@ QWebSocketConfiguration::QWebSocketConfiguration() :
 /*!
     \internal
 */
-QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version, QWebSocket *pWebSocket, QObject *parent) :
-    QObject(parent),
+QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version,
+                                     QWebSocket *pWebSocket) :
+    QObjectPrivate(),
     q_ptr(pWebSocket),
     m_pSocket(),
-    m_errorString(),
+    m_errorString(QWebSocket::tr("Unknown error")),
     m_version(version),
     m_resourceName(),
     m_requestUrl(),
@@ -97,25 +99,26 @@ QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::
     m_protocol(),
     m_extension(),
     m_socketState(QAbstractSocket::UnconnectedState),
+    m_pauseMode(QAbstractSocket::PauseNever),
+    m_readBufferSize(0),
     m_key(),
     m_mustMask(true),
     m_isClosingHandshakeSent(false),
     m_isClosingHandshakeReceived(false),
-    m_closeCode(QWebSocketProtocol::CC_NORMAL),
+    m_closeCode(QWebSocketProtocol::CloseCodeNormal),
     m_closeReason(),
     m_pingTimer(),
     m_dataProcessor(),
     m_configuration()
 {
-    Q_ASSERT(pWebSocket);
-    qsrand(static_cast<uint>(QDateTime::currentMSecsSinceEpoch()));
 }
 
 /*!
     \internal
 */
-QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version, QWebSocket *pWebSocket, QObject *parent) :
-    QObject(parent),
+QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version,
+                                     QWebSocket *pWebSocket) :
+    QObjectPrivate(),
     q_ptr(pWebSocket),
     m_pSocket(pTcpSocket),
     m_errorString(pTcpSocket->errorString()),
@@ -126,18 +129,32 @@ QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol:
     m_protocol(),
     m_extension(),
     m_socketState(pTcpSocket->state()),
+    m_pauseMode(pTcpSocket->pauseMode()),
+    m_readBufferSize(pTcpSocket->readBufferSize()),
     m_key(),
     m_mustMask(true),
     m_isClosingHandshakeSent(false),
     m_isClosingHandshakeReceived(false),
-    m_closeCode(QWebSocketProtocol::CC_NORMAL),
+    m_closeCode(QWebSocketProtocol::CloseCodeNormal),
     m_closeReason(),
     m_pingTimer(),
     m_dataProcessor(),
     m_configuration()
 {
-    Q_ASSERT(pWebSocket);
-    makeConnections(m_pSocket.data());
+}
+
+/*!
+    \internal
+*/
+void QWebSocketPrivate::init()
+{
+    Q_ASSERT(q_ptr);
+    //TODO: need a better randomizer
+    qsrand(static_cast<uint>(QDateTime::currentMSecsSinceEpoch()));
+
+    if (m_pSocket) {
+        makeConnections(m_pSocket.data());
+    }
 }
 
 /*!
@@ -145,12 +162,10 @@ QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol:
 */
 QWebSocketPrivate::~QWebSocketPrivate()
 {
-    if (!m_pSocket) {
+    if (!m_pSocket)
         return;
-    }
-    if (state() == QAbstractSocket::ConnectedState) {
-        close(QWebSocketProtocol::CC_GOING_AWAY, tr("Connection closed"));
-    }
+    if (state() == QAbstractSocket::ConnectedState)
+        close(QWebSocketProtocol::CloseCodeGoingAway, QWebSocket::tr("Connection closed"));
     releaseConnections(m_pSocket.data());
 }
 
@@ -159,9 +174,8 @@ QWebSocketPrivate::~QWebSocketPrivate()
  */
 void QWebSocketPrivate::abort()
 {
-    if (m_pSocket) {
+    if (m_pSocket)
         m_pSocket->abort();
-    }
 }
 
 /*!
@@ -169,10 +183,9 @@ void QWebSocketPrivate::abort()
  */
 QAbstractSocket::SocketError QWebSocketPrivate::error() const
 {
-    QAbstractSocket::SocketError err = QAbstractSocket::OperationError;
-    if (Q_LIKELY(m_pSocket)) {
+    QAbstractSocket::SocketError err = QAbstractSocket::UnknownSocketError;
+    if (Q_LIKELY(m_pSocket))
         err = m_pSocket->error();
-    }
     return err;
 }
 
@@ -182,11 +195,10 @@ QAbstractSocket::SocketError QWebSocketPrivate::error() const
 QString QWebSocketPrivate::errorString() const
 {
     QString errMsg;
-    if (!m_errorString.isEmpty()) {
+    if (!m_errorString.isEmpty())
         errMsg = m_errorString;
-    } else if (m_pSocket) {
+    else if (m_pSocket)
         errMsg = m_pSocket->errorString();
-    }
     return errMsg;
 }
 
@@ -196,39 +208,15 @@ QString QWebSocketPrivate::errorString() const
 bool QWebSocketPrivate::flush()
 {
     bool result = true;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         result = m_pSocket->flush();
-    }
     return result;
 }
 
 /*!
     \internal
  */
-qint64 QWebSocketPrivate::write(const char *message)
-{
-    if (!message || !*message)
-        return qint64(0);
-    uint size = qstrlen(message);
-    qint64 maxSize = qMin(qint64(size), qint64(std::numeric_limits<QString::size_type>::max()));
-    return doWriteFrames(QString::fromUtf8(message, maxSize).toUtf8(), false);
-}
-
-/*!
-    \internal
- */
-qint64 QWebSocketPrivate::write(const char *message, qint64 maxSize)
-{
-    if (!message || (maxSize <= qint64(0)) || !*message)
-        return qint64(0);
-    maxSize = qMin(maxSize, qint64(std::numeric_limits<QString::size_type>::max()));
-    return doWriteFrames(QString::fromUtf8(message, maxSize).toUtf8(), false);
-}
-
-/*!
-    \internal
- */
-qint64 QWebSocketPrivate::write(const QString &message)
+qint64 QWebSocketPrivate::sendTextMessage(const QString &message)
 {
     return doWriteFrames(message.toUtf8(), false);
 }
@@ -236,7 +224,7 @@ qint64 QWebSocketPrivate::write(const QString &message)
 /*!
     \internal
  */
-qint64 QWebSocketPrivate::write(const QByteArray &data)
+qint64 QWebSocketPrivate::sendBinaryMessage(const QByteArray &data)
 {
     return doWriteFrames(data, true);
 }
@@ -274,9 +262,8 @@ void QWebSocketPrivate::ignoreSslErrors()
     m_configuration.m_ignoreSslErrors = true;
     if (Q_LIKELY(m_pSocket)) {
         QSslSocket *pSslSocket = qobject_cast<QSslSocket *>(m_pSocket.data());
-        if (Q_LIKELY(pSslSocket)) {
+        if (Q_LIKELY(pSslSocket))
             pSslSocket->ignoreSslErrors();
-        }
     }
 }
 
@@ -310,25 +297,22 @@ QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
  */
 void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
 {
-    if (Q_UNLIKELY(!m_pSocket)) {
+    if (Q_UNLIKELY(!m_pSocket))
         return;
-    }
     if (!m_isClosingHandshakeSent) {
         Q_Q(QWebSocket);
-        quint32 maskingKey = 0;
-        if (m_mustMask) {
-            maskingKey = generateMaskingKey();
-        }
         const quint16 code = qToBigEndian<quint16>(closeCode);
         QByteArray payload;
         payload.append(static_cast<const char *>(static_cast<const void *>(&code)), 2);
-        if (!reason.isEmpty()) {
+        if (!reason.isEmpty())
             payload.append(reason.toUtf8());
-        }
+        quint32 maskingKey = 0;
         if (m_mustMask) {
+            maskingKey = generateMaskingKey();
             QWebSocketProtocol::mask(payload.data(), payload.size(), maskingKey);
         }
-        QByteArray frame = getFrameHeader(QWebSocketProtocol::OC_CLOSE, payload.size(), maskingKey, true);
+        QByteArray frame = getFrameHeader(QWebSocketProtocol::OpCodeClose,
+                                          payload.size(), maskingKey, true);
         frame.append(payload);
         m_pSocket->write(frame);
         m_pSocket->flush();
@@ -345,7 +329,9 @@ void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString r
  */
 void QWebSocketPrivate::open(const QUrl &url, bool mask)
 {
-    //m_pSocket.reset();  //just delete the old socket for the moment; later, we can add more 'intelligent' handling by looking at the url
+    //just delete the old socket for the moment;
+    //later, we can add more 'intelligent' handling by looking at the url
+    //m_pSocket.reset();
     QTcpSocket *pTcpSocket = m_pSocket.take();
     if (pTcpSocket) {
         releaseConnections(pTcpSocket);
@@ -367,69 +353,79 @@ void QWebSocketPrivate::open(const QUrl &url, bool mask)
             }
             resourceName.append(url.query());
         }
-        if (resourceName.isEmpty()) {
+        if (resourceName.isEmpty())
             resourceName = QStringLiteral("/");
-        }
         setResourceName(resourceName);
         enableMasking(mask);
 
     #ifndef QT_NO_SSL
         if (url.scheme() == QStringLiteral("wss")) {
             if (!QSslSocket::supportsSsl()) {
-                const QString message = tr("SSL Sockets are not supported on this platform.");
+                const QString message =
+                        QWebSocket::tr("SSL Sockets are not supported on this platform.");
                 setErrorString(message);
-                emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
+                Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
             } else {
-                QSslSocket *sslSocket = new QSslSocket(this);
+                QSslSocket *sslSocket = new QSslSocket;
                 m_pSocket.reset(sslSocket);
                 if (Q_LIKELY(m_pSocket)) {
                     m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
                     m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
+                    m_pSocket->setReadBufferSize(m_readBufferSize);
+                    m_pSocket->setPauseMode(m_pauseMode);
 
                     makeConnections(m_pSocket.data());
-                    connect(sslSocket, SIGNAL(encryptedBytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
+                    QObject::connect(sslSocket, &QSslSocket::encryptedBytesWritten, q,
+                                     &QWebSocket::bytesWritten);
+                    typedef void (QSslSocket:: *sslErrorSignalType)(const QList<QSslError> &);
+                    QObject::connect(sslSocket,
+                                     static_cast<sslErrorSignalType>(&QSslSocket::sslErrors),
+                                     q, &QWebSocket::sslErrors);
                     setSocketState(QAbstractSocket::ConnectingState);
 
                     sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
-                    if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors)) {
+                    if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors))
                         sslSocket->ignoreSslErrors();
-                    } else {
+                    else
                         sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
-                    }
     #ifndef QT_NO_NETWORKPROXY
                     sslSocket->setProxy(m_configuration.m_proxy);
     #endif
                     sslSocket->connectToHostEncrypted(url.host(), url.port(443));
                 } else {
-                    const QString message = tr("Out of memory.");
+                    const QString message = QWebSocket::tr("Out of memory.");
                     setErrorString(message);
-                    emit q->error(QAbstractSocket::SocketResourceError);
+                    Q_EMIT q->error(QAbstractSocket::SocketResourceError);
                 }
             }
         } else
     #endif
         if (url.scheme() == QStringLiteral("ws")) {
-            m_pSocket.reset(new QTcpSocket(this));
+            m_pSocket.reset(new QTcpSocket);
             if (Q_LIKELY(m_pSocket)) {
                 m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
                 m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
+                m_pSocket->setReadBufferSize(m_readBufferSize);
+                m_pSocket->setPauseMode(m_pauseMode);
 
                 makeConnections(m_pSocket.data());
-                connect(m_pSocket.data(), SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
+                QObject::connect(m_pSocket.data(), &QAbstractSocket::bytesWritten, q,
+                                 &QWebSocket::bytesWritten);
                 setSocketState(QAbstractSocket::ConnectingState);
     #ifndef QT_NO_NETWORKPROXY
                 m_pSocket->setProxy(m_configuration.m_proxy);
     #endif
                 m_pSocket->connectToHost(url.host(), url.port(80));
             } else {
-                const QString message = tr("Out of memory.");
+                const QString message = QWebSocket::tr("Out of memory.");
                 setErrorString(message);
-                emit q->error(QAbstractSocket::SocketResourceError);
+                Q_EMIT q->error(QAbstractSocket::SocketResourceError);
             }
         } else {
-            const QString message = tr("Unsupported websockets scheme: %1").arg(url.scheme());
+            const QString message =
+                    QWebSocket::tr("Unsupported websockets scheme: %1").arg(url.scheme());
             setErrorString(message);
-            emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
+            Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
         }
     }
 }
@@ -437,26 +433,26 @@ void QWebSocketPrivate::open(const QUrl &url, bool mask)
 /*!
     \internal
  */
-void QWebSocketPrivate::ping(QByteArray payload)
+void QWebSocketPrivate::ping(const QByteArray &payload)
 {
-    if (payload.length() > 125) {
-        payload.truncate(125);
-    }
+    QByteArray payloadTruncated = payload.left(125);
     m_pingTimer.restart();
-    QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OC_PING, payload.size(), 0 /*do not mask*/, true);
-    pingFrame.append(payload);
-    (void)writeFrame(pingFrame);
+    QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OpCodePing, payloadTruncated.size(),
+                                          0 /*do not mask*/, true);
+    pingFrame.append(payloadTruncated);
+    qint64 ret = writeFrame(pingFrame);
+    Q_UNUSED(ret);
 }
 
 /*!
   \internal
-    Sets the version to use for the websocket protocol; this must be set before the socket is opened.
+    Sets the version to use for the websocket protocol;
+    this must be set before the socket is opened.
 */
 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
 {
-    if (m_version != version) {
+    if (m_version != version)
         m_version = version;
-    }
 }
 
 /*!
@@ -465,9 +461,8 @@ void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
 */
 void QWebSocketPrivate::setResourceName(const QString &resourceName)
 {
-    if (m_resourceName != resourceName) {
+    if (m_resourceName != resourceName)
         m_resourceName = resourceName;
-    }
 }
 
 /*!
@@ -475,9 +470,8 @@ void QWebSocketPrivate::setResourceName(const QString &resourceName)
  */
 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
 {
-    if (m_requestUrl != requestUrl) {
+    if (m_requestUrl != requestUrl)
         m_requestUrl = requestUrl;
-    }
 }
 
 /*!
@@ -485,9 +479,8 @@ void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
  */
 void QWebSocketPrivate::setOrigin(const QString &origin)
 {
-    if (m_origin != origin) {
+    if (m_origin != origin)
         m_origin = origin;
-    }
 }
 
 /*!
@@ -495,9 +488,8 @@ void QWebSocketPrivate::setOrigin(const QString &origin)
  */
 void QWebSocketPrivate::setProtocol(const QString &protocol)
 {
-    if (m_protocol != protocol) {
+    if (m_protocol != protocol)
         m_protocol = protocol;
-    }
 }
 
 /*!
@@ -505,9 +497,8 @@ void QWebSocketPrivate::setProtocol(const QString &protocol)
  */
 void QWebSocketPrivate::setExtension(const QString &extension)
 {
-    if (m_extension != extension) {
+    if (m_extension != extension)
         m_extension = extension;
-    }
 }
 
 /*!
@@ -515,9 +506,8 @@ void QWebSocketPrivate::setExtension(const QString &extension)
  */
 void QWebSocketPrivate::enableMasking(bool enable)
 {
-    if (m_mustMask != enable) {
+    if (m_mustMask != enable)
         m_mustMask = enable;
-    }
 }
 
 /*!
@@ -530,25 +520,42 @@ void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
 
     if (Q_LIKELY(pTcpSocket)) {
         //pass through signals
-        connect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SIGNAL(error(QAbstractSocket::SocketError)));
-        connect(pTcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), q, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
-        connect(pTcpSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
-        connect(pTcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
+        typedef void (QAbstractSocket:: *ASErrorSignal)(QAbstractSocket::SocketError);
+        typedef void (QWebSocket:: *WSErrorSignal)(QAbstractSocket::SocketError);
+        QObject::connect(pTcpSocket,
+                         static_cast<ASErrorSignal>(&QAbstractSocket::error),
+                         q, static_cast<WSErrorSignal>(&QWebSocket::error));
+        QObject::connect(pTcpSocket, &QAbstractSocket::proxyAuthenticationRequired, q,
+                         &QWebSocket::proxyAuthenticationRequired);
+        QObject::connect(pTcpSocket, &QAbstractSocket::readChannelFinished, q,
+                         &QWebSocket::readChannelFinished);
+        QObject::connect(pTcpSocket, &QAbstractSocket::aboutToClose, q, &QWebSocket::aboutToClose);
 
         //catch signals
-        connect(pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processStateChanged(QAbstractSocket::SocketState)));
-        //!!!important to use a QueuedConnection here; with QTcpSocket there is no problem, but with QSslSocket the processing hangs
-        connect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(processData()), Qt::QueuedConnection);
-    }
-
-    connect(&m_dataProcessor, SIGNAL(textFrameReceived(QString,bool)), q, SIGNAL(textFrameReceived(QString,bool)));
-    connect(&m_dataProcessor, SIGNAL(binaryFrameReceived(QByteArray,bool)), q, SIGNAL(binaryFrameReceived(QByteArray,bool)));
-    connect(&m_dataProcessor, SIGNAL(binaryMessageReceived(QByteArray)), q, SIGNAL(binaryMessageReceived(QByteArray)));
-    connect(&m_dataProcessor, SIGNAL(textMessageReceived(QString)), q, SIGNAL(textMessageReceived(QString)));
-    connect(&m_dataProcessor, SIGNAL(errorEncountered(QWebSocketProtocol::CloseCode,QString)), this, SLOT(close(QWebSocketProtocol::CloseCode,QString)));
-    connect(&m_dataProcessor, SIGNAL(pingReceived(QByteArray)), this, SLOT(processPing(QByteArray)));
-    connect(&m_dataProcessor, SIGNAL(pongReceived(QByteArray)), this, SLOT(processPong(QByteArray)));
-    connect(&m_dataProcessor, SIGNAL(closeReceived(QWebSocketProtocol::CloseCode,QString)), this, SLOT(processClose(QWebSocketProtocol::CloseCode,QString)));
+        QObjectPrivate::connect(pTcpSocket, &QAbstractSocket::stateChanged, this,
+                                &QWebSocketPrivate::processStateChanged);
+        //!!!important to use a QueuedConnection here;
+        //with QTcpSocket there is no problem, but with QSslSocket the processing hangs
+        QObjectPrivate::connect(pTcpSocket, &QAbstractSocket::readyRead, this,
+                                &QWebSocketPrivate::processData, Qt::QueuedConnection);
+    }
+
+    QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::textFrameReceived, q,
+                     &QWebSocket::textFrameReceived);
+    QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryFrameReceived, q,
+                     &QWebSocket::binaryFrameReceived);
+    QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryMessageReceived, q,
+                     &QWebSocket::binaryMessageReceived);
+    QObject::connect(&m_dataProcessor, &QWebSocketDataProcessor::textMessageReceived, q,
+                     &QWebSocket::textMessageReceived);
+    QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::errorEncountered, this,
+                            &QWebSocketPrivate::close);
+    QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::pingReceived, this,
+                            &QWebSocketPrivate::processPing);
+    QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::pongReceived, this,
+                            &QWebSocketPrivate::processPong);
+    QObjectPrivate::connect(&m_dataProcessor, &QWebSocketDataProcessor::closeReceived, this,
+                            &QWebSocketPrivate::processClose);
 }
 
 /*!
@@ -556,10 +563,9 @@ void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
  */
 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
 {
-    if (Q_LIKELY(pTcpSocket)) {
-        disconnect(pTcpSocket);
-    }
-    disconnect(&m_dataProcessor);
+    if (Q_LIKELY(pTcpSocket))
+        pTcpSocket->disconnect(pTcpSocket);
+    m_dataProcessor.disconnect(&m_dataProcessor);
 }
 
 /*!
@@ -629,22 +635,22 @@ QString QWebSocketPrivate::closeReason() const
 /*!
  * \internal
  */
-QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode, quint64 payloadLength, quint32 maskingKey, bool lastFrame)
+QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
+                                             quint64 payloadLength, quint32 maskingKey,
+                                             bool lastFrame)
 {
     QByteArray header;
     quint8 byte = 0x00;
     bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
 
     if (Q_LIKELY(ok)) {
-        //FIN, RSV1-3, opcode
-        byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00));       //FIN, opcode
-        //RSV-1, RSV-2 and RSV-3 are zero
+        //FIN, RSV1-3, opcode (RSV-1, RSV-2 and RSV-3 are zero)
+        byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00));
         header.append(static_cast<char>(byte));
 
         byte = 0x00;
-        if (maskingKey != 0) {
+        if (maskingKey != 0)
             byte |= 0x80;
-        }
         if (payloadLength <= 125) {
             byte |= static_cast<quint8>(payloadLength);
             header.append(static_cast<char>(byte));
@@ -662,7 +668,8 @@ QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
 
         if (maskingKey != 0) {
             const quint32 mask = qToBigEndian<quint32>(maskingKey);
-            header.append(static_cast<const char *>(static_cast<const void *>(&mask)), sizeof(quint32));
+            header.append(static_cast<const char *>(static_cast<const void *>(&mask)),
+                          sizeof(quint32));
         }
     } else {
         setErrorString(QStringLiteral("WebSocket::getHeader: payload too big!"));
@@ -678,41 +685,40 @@ QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
 {
     qint64 payloadWritten = 0;
-    if (Q_UNLIKELY(!m_pSocket)) {
+    if (Q_UNLIKELY(!m_pSocket) || (state() != QAbstractSocket::ConnectedState))
         return payloadWritten;
-    }
+
     Q_Q(QWebSocket);
     const QWebSocketProtocol::OpCode firstOpCode = isBinary ?
-                QWebSocketProtocol::OC_BINARY : QWebSocketProtocol::OC_TEXT;
+                QWebSocketProtocol::OpCodeBinary : QWebSocketProtocol::OpCodeText;
 
     int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
     QByteArray tmpData(data);
     tmpData.detach();
     char *payload = tmpData.data();
     quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES;
-    if (Q_LIKELY(sizeLeft)) {
+    if (Q_LIKELY(sizeLeft))
         ++numFrames;
-    }
+
     //catch the case where the payload is zero bytes;
     //in this case, we still need to send a frame
-    if (Q_UNLIKELY(numFrames == 0)) {
+    if (Q_UNLIKELY(numFrames == 0))
         numFrames = 1;
-    }
     quint64 currentPosition = 0;
     qint64 bytesWritten = 0;
     quint64 bytesLeft = data.size();
 
     for (int i = 0; i < numFrames; ++i) {
         quint32 maskingKey = 0;
-        if (m_mustMask) {
+        if (m_mustMask)
             maskingKey = generateMaskingKey();
-        }
 
         const bool isLastFrame = (i == (numFrames - 1));
         const bool isFirstFrame = (i == 0);
 
         const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
-        const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode : QWebSocketProtocol::OC_CONTINUE;
+        const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode
+                                                               : QWebSocketProtocol::OpCodeContinue;
 
         //write header
         bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
@@ -720,16 +726,16 @@ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
         //write payload
         if (Q_LIKELY(size > 0)) {
             char *currentData = payload + currentPosition;
-            if (m_mustMask) {
+            if (m_mustMask)
                 QWebSocketProtocol::mask(currentData, size, maskingKey);
-            }
             qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
             if (Q_LIKELY(written > 0)) {
                 bytesWritten += written;
                 payloadWritten += written;
             } else {
                 m_pSocket->flush();
-                setErrorString(tr("Error writing bytes to socket: %1.").arg(m_pSocket->errorString()));
+                setErrorString(QWebSocket::tr("Error writing bytes to socket: %1.")
+                               .arg(m_pSocket->errorString()));
                 Q_EMIT q->error(QAbstractSocket::NetworkError);
                 break;
             }
@@ -738,7 +744,8 @@ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
         bytesLeft -= size;
     }
     if (Q_UNLIKELY(payloadWritten != data.size())) {
-        setErrorString(tr("Bytes written %1 != %2.").arg(payloadWritten).arg(data.size()));
+        setErrorString(QWebSocket::tr("Bytes written %1 != %2.")
+                       .arg(payloadWritten).arg(data.size()));
         Q_EMIT q->error(QAbstractSocket::NetworkError);
     }
     return payloadWritten;
@@ -749,6 +756,7 @@ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
  */
 quint32 QWebSocketPrivate::generateRandomNumber() const
 {
+    //TODO: need a better randomizer
     return quint32((double(qrand()) / RAND_MAX) * std::numeric_limits<quint32>::max());
 }
 
@@ -794,9 +802,8 @@ qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
     qint64 written = 0;
     if (Q_LIKELY(m_pSocket)) {
         QList<QByteArray>::const_iterator it;
-        for (it = frames.cbegin(); it < frames.cend(); ++it) {
+        for (it = frames.cbegin(); it < frames.cend(); ++it)
             written += writeFrame(*it);
-        }
     }
     return written;
 }
@@ -807,9 +814,8 @@ qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
 {
     qint64 written = 0;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         written = m_pSocket->write(frame);
-    }
     return written;
 }
 
@@ -839,9 +845,8 @@ QString readLine(QTcpSocket *pSocket)
 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
 {
     Q_Q(QWebSocket);
-    if (!pSocket) {
+    if (Q_UNLIKELY(!pSocket))
         return;
-    }
 
     bool ok = false;
     QString errorDescription;
@@ -864,23 +869,30 @@ void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
         }
     }
     if (Q_UNLIKELY(!ok)) {
-        errorDescription = tr("Invalid statusline in response: %1.").arg(statusLine);
+        errorDescription = QWebSocket::tr("Invalid statusline in response: %1.").arg(statusLine);
     } else {
         QString headerLine = readLine(pSocket);
         QMap<QString, QString> headers;
         while (!headerLine.isEmpty()) {
-            const QStringList headerField = headerLine.split(QStringLiteral(": "), QString::SkipEmptyParts);
-            headers.insertMulti(headerField[0], headerField[1]);
+            const QStringList headerField = headerLine.split(QStringLiteral(": "),
+                                                             QString::SkipEmptyParts);
+            if (headerField.size() == 2) {
+                headers.insertMulti(headerField[0], headerField[1]);
+            }
             headerLine = readLine(pSocket);
         }
 
-        const QString acceptKey = headers.value(QStringLiteral("Sec-WebSocket-Accept"), QStringLiteral(""));
-        const QString upgrade = headers.value(QStringLiteral("Upgrade"), QStringLiteral(""));
-        const QString connection = headers.value(QStringLiteral("Connection"), QStringLiteral(""));
-        //unused for the moment
-        //const QString extensions = headers.value(QStringLiteral("Sec-WebSocket-Extensions"), QStringLiteral(""));
-        //const QString protocol = headers.value(QStringLiteral("Sec-WebSocket-Protocol"), QStringLiteral(""));
-        const QString version = headers.value(QStringLiteral("Sec-WebSocket-Version"), QStringLiteral(""));
+        const QString acceptKey = headers.value(QStringLiteral("Sec-WebSocket-Accept"),
+                                                QString());
+        const QString upgrade = headers.value(QStringLiteral("Upgrade"), QString());
+        const QString connection = headers.value(QStringLiteral("Connection"), QString());
+//        unused for the moment
+//        const QString extensions = headers.value(QStringLiteral("Sec-WebSocket-Extensions"),
+//                                                 QString());
+//        const QString protocol = headers.value(QStringLiteral("Sec-WebSocket-Protocol"),
+//                                               QString());
+        const QString version = headers.value(QStringLiteral("Sec-WebSocket-Version"),
+                                              QString());
 
         if (Q_LIKELY(httpStatusCode == 101)) {
             //HTTP/x.y 101 Switching Protocols
@@ -894,29 +906,38 @@ void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
             if (ok) {
                 const QString accept = calculateAcceptKey(m_key);
                 ok = (accept == acceptKey);
-                if (!ok) {
-                    errorDescription = tr("Accept-Key received from server %1 does not match the client key %2.").arg(acceptKey).arg(accept);
-                }
+                if (!ok)
+                    errorDescription =
+                      QWebSocket::tr("Accept-Key received from server %1 does not match the client key %2.")
+                            .arg(acceptKey).arg(accept);
             } else {
-                errorDescription = tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.").arg(statusLine);
+                errorDescription =
+                    QWebSocket::tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.")
+                        .arg(statusLine);
             }
         } else if (httpStatusCode == 400) {
             //HTTP/1.1 400 Bad Request
             if (!version.isEmpty()) {
-                const QStringList versions = version.split(QStringLiteral(", "), QString::SkipEmptyParts);
+                const QStringList versions = version.split(QStringLiteral(", "),
+                                                           QString::SkipEmptyParts);
                 if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion()))) {
                     //if needed to switch protocol version, then we are finished here
                     //because we cannot handle other protocols than the RFC one (v13)
-                    errorDescription = tr("Handshake: Server requests a version that we don't support: %1.").arg(versions.join(QStringLiteral(", ")));
+                    errorDescription =
+                            QWebSocket::tr("Handshake: Server requests a version that we don't support: %1.")
+                            .arg(versions.join(QStringLiteral(", ")));
                     ok = false;
                 } else {
                     //we tried v13, but something different went wrong
-                    errorDescription = tr("QWebSocketPrivate::processHandshake: Unknown error condition encountered. Aborting connection.");
+                    errorDescription =
+                        QWebSocket::tr("QWebSocketPrivate::processHandshake: Unknown error condition encountered. Aborting connection.");
                     ok = false;
                 }
             }
         } else {
-            errorDescription = tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).").arg(httpStatusCode).arg(httpStatusMessage);
+            errorDescription =
+                    QWebSocket::tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).")
+                        .arg(httpStatusCode).arg(httpStatusMessage);
             ok = false;
         }
 
@@ -939,57 +960,47 @@ void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketS
     Q_ASSERT(m_pSocket);
     Q_Q(QWebSocket);
     QAbstractSocket::SocketState webSocketState = this->state();
-    switch (socketState)
-    {
+    switch (socketState) {
     case QAbstractSocket::ConnectedState:
-    {
         if (webSocketState == QAbstractSocket::ConnectingState) {
             m_key = generateKey();
-            const QString handshake = createHandShakeRequest(m_resourceName, m_requestUrl.host() % QStringLiteral(":") % QString::number(m_requestUrl.port(80)), origin(), QStringLiteral(""), QStringLiteral(""), m_key);
+            const QString handshake =
+                    createHandShakeRequest(m_resourceName,
+                                           m_requestUrl.host()
+                                                % QStringLiteral(":")
+                                                % QString::number(m_requestUrl.port(80)),
+                                           origin(),
+                                           QString(),
+                                           QString(),
+                                           m_key);
             m_pSocket->write(handshake.toLatin1());
         }
         break;
-    }
+
     case QAbstractSocket::ClosingState:
-    {
-        if (webSocketState == QAbstractSocket::ConnectedState) {
+        if (webSocketState == QAbstractSocket::ConnectedState)
             setSocketState(QAbstractSocket::ClosingState);
-        }
         break;
-    }
+
     case QAbstractSocket::UnconnectedState:
-    {
         if (webSocketState != QAbstractSocket::UnconnectedState) {
             setSocketState(QAbstractSocket::UnconnectedState);
             Q_EMIT q->disconnected();
         }
         break;
-    }
+
     case QAbstractSocket::HostLookupState:
     case QAbstractSocket::ConnectingState:
     case QAbstractSocket::BoundState:
     case QAbstractSocket::ListeningState:
-    {
         //do nothing
         //to make C++ compiler happy;
         break;
-    }
     default:
-    {
         break;
     }
-    }
 }
 
-//order of events:
-//connectToHost is called
-//our socket state is set to "connecting", and tcpSocket->connectToHost is called
-//the tcpsocket is opened, a handshake message is sent; a readyRead signal is thrown
-//this signal is catched by processData
-//when OUR socket state is in the "connecting state", this means that
-//we have received data from the server (response to handshake), and that we
-//should "upgrade" our socket to a websocket (connected state)
-//if our socket was already upgraded, then we need to process websocket data
 /*!
  \internal
  */
@@ -997,37 +1008,35 @@ void QWebSocketPrivate::processData()
 {
     Q_ASSERT(m_pSocket);
     while (m_pSocket->bytesAvailable()) {
-        if (state() == QAbstractSocket::ConnectingState) {
+        if (state() == QAbstractSocket::ConnectingState)
             processHandshake(m_pSocket.data());
-        } else {
+        else
             m_dataProcessor.process(m_pSocket.data());
-        }
     }
 }
 
 /*!
  \internal
  */
-void QWebSocketPrivate::processPing(QByteArray data)
+void QWebSocketPrivate::processPing(const QByteArray &data)
 {
     Q_ASSERT(m_pSocket);
     quint32 maskingKey = 0;
-    if (m_mustMask) {
+    if (m_mustMask)
         maskingKey = generateMaskingKey();
-    }
-    m_pSocket->write(getFrameHeader(QWebSocketProtocol::OC_PONG, data.size(), maskingKey, true));
+    m_pSocket->write(getFrameHeader(QWebSocketProtocol::OpCodePong, data.size(), maskingKey, true));
     if (data.size() > 0) {
-        if (m_mustMask) {
-            QWebSocketProtocol::mask(&data, maskingKey);
-        }
-        m_pSocket->write(data);
+        QByteArray maskedData = data;
+        if (m_mustMask)
+            QWebSocketProtocol::mask(&maskedData, maskingKey);
+        m_pSocket->write(maskedData);
     }
 }
 
 /*!
  \internal
  */
-void QWebSocketPrivate::processPong(QByteArray data)
+void QWebSocketPrivate::processPong(const QByteArray &data)
 {
     Q_Q(QWebSocket);
     Q_EMIT q->pong(static_cast<quint64>(m_pingTimer.elapsed()), data);
@@ -1059,16 +1068,14 @@ QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
                         QStringLiteral("Upgrade: websocket") <<
                         QStringLiteral("Connection: Upgrade") <<
                         QStringLiteral("Sec-WebSocket-Key: ") % QString::fromLatin1(key);
-    if (!origin.isEmpty()) {
+    if (!origin.isEmpty())
         handshakeRequest << QStringLiteral("Origin: ") % origin;
-    }
-    handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ") % QString::number(QWebSocketProtocol::currentVersion());
-    if (extensions.length() > 0) {
+    handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ")
+                            % QString::number(QWebSocketProtocol::currentVersion());
+    if (extensions.length() > 0)
         handshakeRequest << QStringLiteral("Sec-WebSocket-Extensions: ") % extensions;
-    }
-    if (protocols.length() > 0) {
+    if (protocols.length() > 0)
         handshakeRequest << QStringLiteral("Sec-WebSocket-Protocol: ") % protocols;
-    }
     handshakeRequest << QStringLiteral("\r\n");
 
     return handshakeRequest.join(QStringLiteral("\r\n"));
@@ -1085,30 +1092,6 @@ QAbstractSocket::SocketState QWebSocketPrivate::state() const
 /*!
     \internal
  */
-bool QWebSocketPrivate::waitForConnected(int msecs)
-{
-    bool result = false;
-    if (Q_LIKELY(m_pSocket)) {
-        result = m_pSocket->waitForConnected(msecs);
-    }
-    return result;
-}
-
-/*!
-    \internal
- */
-bool QWebSocketPrivate::waitForDisconnected(int msecs)
-{
-    bool result = false;
-    if (Q_LIKELY(m_pSocket)) {
-        result = m_pSocket->waitForDisconnected(msecs);
-    }
-    return result;
-}
-
-/*!
-    \internal
- */
 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
 {
     Q_Q(QWebSocket);
@@ -1123,9 +1106,8 @@ void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
  */
 void QWebSocketPrivate::setErrorString(const QString &errorString)
 {
-    if (m_errorString != errorString) {
+    if (m_errorString != errorString)
         m_errorString = errorString;
-    }
 }
 
 /*!
@@ -1134,9 +1116,8 @@ void QWebSocketPrivate::setErrorString(const QString &errorString)
 QHostAddress QWebSocketPrivate::localAddress() const
 {
     QHostAddress address;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         address = m_pSocket->localAddress();
-    }
     return address;
 }
 
@@ -1146,9 +1127,8 @@ QHostAddress QWebSocketPrivate::localAddress() const
 quint16 QWebSocketPrivate::localPort() const
 {
     quint16 port = 0;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         port = m_pSocket->localPort();
-    }
     return port;
 }
 
@@ -1157,11 +1137,7 @@ quint16 QWebSocketPrivate::localPort() const
  */
 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
 {
-    QAbstractSocket::PauseModes mode = QAbstractSocket::PauseNever;
-    if (Q_LIKELY(m_pSocket)) {
-        mode = m_pSocket->pauseMode();
-    }
-    return mode;
+    return m_pauseMode;
 }
 
 /*!
@@ -1170,9 +1146,8 @@ QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
 QHostAddress QWebSocketPrivate::peerAddress() const
 {
     QHostAddress address;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         address = m_pSocket->peerAddress();
-    }
     return address;
 }
 
@@ -1182,9 +1157,8 @@ QHostAddress QWebSocketPrivate::peerAddress() const
 QString QWebSocketPrivate::peerName() const
 {
     QString name;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         name = m_pSocket->peerName();
-    }
     return name;
 }
 
@@ -1194,9 +1168,8 @@ QString QWebSocketPrivate::peerName() const
 quint16 QWebSocketPrivate::peerPort() const
 {
     quint16 port = 0;
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         port = m_pSocket->peerPort();
-    }
     return port;
 }
 
@@ -1214,9 +1187,8 @@ QNetworkProxy QWebSocketPrivate::proxy() const
  */
 void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
 {
-    if (networkProxy != networkProxy) {
+    if (networkProxy != networkProxy)
         m_configuration.m_proxy = networkProxy;
-    }
 }
 #endif  //QT_NO_NETWORKPROXY
 
@@ -1225,11 +1197,7 @@ void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
  */
 qint64 QWebSocketPrivate::readBufferSize() const
 {
-    qint64 size = 0;
-    if (Q_LIKELY(m_pSocket)) {
-        size = m_pSocket->readBufferSize();
-    }
-    return size;
+    return m_readBufferSize;
 }
 
 /*!
@@ -1237,9 +1205,8 @@ qint64 QWebSocketPrivate::readBufferSize() const
  */
 void QWebSocketPrivate::resume()
 {
-    if (Q_LIKELY(m_pSocket)) {
+    if (Q_LIKELY(m_pSocket))
         m_pSocket->resume();
-    }
 }
 
 /*!
@@ -1247,9 +1214,9 @@ void QWebSocketPrivate::resume()
  */
 void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
 {
-    if (Q_LIKELY(m_pSocket)) {
-        m_pSocket->setPauseMode(pauseMode);
-    }
+    m_pauseMode = pauseMode;
+    if (Q_LIKELY(m_pSocket))
+        m_pSocket->setPauseMode(m_pauseMode);
 }
 
 /*!
@@ -1257,31 +1224,9 @@ void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
  */
 void QWebSocketPrivate::setReadBufferSize(qint64 size)
 {
-    if (Q_LIKELY(m_pSocket)) {
-        m_pSocket->setReadBufferSize(size);
-    }
-}
-
-/*!
-    \internal
- */
-void QWebSocketPrivate::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
-{
-    if (Q_LIKELY(m_pSocket)) {
-        m_pSocket->setSocketOption(option, value);
-    }
-}
-
-/*!
-    \internal
- */
-QVariant QWebSocketPrivate::socketOption(QAbstractSocket::SocketOption option)
-{
-    QVariant val;
-    if (Q_LIKELY(m_pSocket)) {
-        val = m_pSocket->socketOption(option);
-    }
-    return val;
+    m_readBufferSize = size;
+    if (Q_LIKELY(m_pSocket))
+        m_pSocket->setReadBufferSize(m_readBufferSize);
 }
 
 /*!
@@ -1289,7 +1234,8 @@ QVariant QWebSocketPrivate::socketOption(QAbstractSocket::SocketOption option)
  */
 bool QWebSocketPrivate::isValid() const
 {
-    return (m_pSocket && m_pSocket->isValid());
+    return (m_pSocket && m_pSocket->isValid() &&
+            (m_socketState == QAbstractSocket::ConnectedState));
 }
 
 QT_END_NAMESPACE