Update license headers and add new license files
[contrib/qtwebsockets.git] / src / websockets / qwebsocket_p.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
7 **
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.
16 **
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.
25 **
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.
29 **
30 ** $QT_END_LICENSE$
31 **
32 ****************************************************************************/
33
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"
40
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>
53 #endif
54 #ifndef QT_NO_SSL
55 #include <QtNetwork/QSslConfiguration>
56 #include <QtNetwork/QSslError>
57 #endif
58
59 #include <QtCore/QDebug>
60
61 #include <limits>
62
63 QT_BEGIN_NAMESPACE
64
65 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2;      //maximum size of a frame when sending a message
66
67 QWebSocketConfiguration::QWebSocketConfiguration() :
68 #ifndef QT_NO_SSL
69     m_sslConfiguration(QSslConfiguration::defaultConfiguration()),
70     m_ignoredSslErrors(),
71     m_ignoreSslErrors(false),
72 #endif
73 #ifndef QT_NO_NETWORKPROXY
74     m_proxy(QNetworkProxy::DefaultProxy),
75 #endif
76     m_pSocket(Q_NULLPTR)
77 {
78 }
79
80 /*!
81     \internal
82 */
83 QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version,
84                                      QWebSocket *pWebSocket) :
85     QObjectPrivate(),
86     q_ptr(pWebSocket),
87     m_pSocket(),
88     m_errorString(),
89     m_version(version),
90     m_resourceName(),
91     m_requestUrl(),
92     m_origin(origin),
93     m_protocol(),
94     m_extension(),
95     m_socketState(QAbstractSocket::UnconnectedState),
96     m_pauseMode(QAbstractSocket::PauseNever),
97     m_readBufferSize(0),
98     m_key(),
99     m_mustMask(true),
100     m_isClosingHandshakeSent(false),
101     m_isClosingHandshakeReceived(false),
102     m_closeCode(QWebSocketProtocol::CloseCodeNormal),
103     m_closeReason(),
104     m_pingTimer(),
105     m_dataProcessor(),
106     m_configuration(),
107     m_pMaskGenerator(&m_defaultMaskGenerator),
108     m_defaultMaskGenerator()
109 {
110 }
111
112 /*!
113     \internal
114 */
115 QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version,
116                                      QWebSocket *pWebSocket) :
117     QObjectPrivate(),
118     q_ptr(pWebSocket),
119     m_pSocket(pTcpSocket),
120     m_errorString(pTcpSocket->errorString()),
121     m_version(version),
122     m_resourceName(),
123     m_requestUrl(),
124     m_origin(),
125     m_protocol(),
126     m_extension(),
127     m_socketState(pTcpSocket->state()),
128     m_pauseMode(pTcpSocket->pauseMode()),
129     m_readBufferSize(pTcpSocket->readBufferSize()),
130     m_key(),
131     m_mustMask(true),
132     m_isClosingHandshakeSent(false),
133     m_isClosingHandshakeReceived(false),
134     m_closeCode(QWebSocketProtocol::CloseCodeNormal),
135     m_closeReason(),
136     m_pingTimer(),
137     m_dataProcessor(),
138     m_configuration(),
139     m_pMaskGenerator(&m_defaultMaskGenerator),
140     m_defaultMaskGenerator()
141 {
142 }
143
144 /*!
145     \internal
146 */
147 void QWebSocketPrivate::init()
148 {
149     Q_ASSERT(q_ptr);
150     Q_ASSERT(m_pMaskGenerator);
151
152     m_pMaskGenerator->seed();
153
154     if (m_pSocket) {
155         makeConnections(m_pSocket.data());
156     }
157 }
158
159 /*!
160     \internal
161 */
162 QWebSocketPrivate::~QWebSocketPrivate()
163 {
164     if (!m_pSocket)
165         return;
166     if (state() == QAbstractSocket::ConnectedState)
167         close(QWebSocketProtocol::CloseCodeGoingAway, QWebSocket::tr("Connection closed"));
168     releaseConnections(m_pSocket.data());
169 }
170
171 /*!
172     \internal
173  */
174 void QWebSocketPrivate::abort()
175 {
176     if (m_pSocket)
177         m_pSocket->abort();
178 }
179
180 /*!
181     \internal
182  */
183 QAbstractSocket::SocketError QWebSocketPrivate::error() const
184 {
185     QAbstractSocket::SocketError err = QAbstractSocket::UnknownSocketError;
186     if (Q_LIKELY(m_pSocket))
187         err = m_pSocket->error();
188     return err;
189 }
190
191 /*!
192     \internal
193  */
194 QString QWebSocketPrivate::errorString() const
195 {
196     QString errMsg;
197     if (!m_errorString.isEmpty())
198         errMsg = m_errorString;
199     else if (m_pSocket)
200         errMsg = m_pSocket->errorString();
201     return errMsg;
202 }
203
204 /*!
205     \internal
206  */
207 bool QWebSocketPrivate::flush()
208 {
209     bool result = true;
210     if (Q_LIKELY(m_pSocket))
211         result = m_pSocket->flush();
212     return result;
213 }
214
215 /*!
216     \internal
217  */
218 qint64 QWebSocketPrivate::sendTextMessage(const QString &message)
219 {
220     return doWriteFrames(message.toUtf8(), false);
221 }
222
223 /*!
224     \internal
225  */
226 qint64 QWebSocketPrivate::sendBinaryMessage(const QByteArray &data)
227 {
228     return doWriteFrames(data, true);
229 }
230
231 #ifndef QT_NO_SSL
232 /*!
233     \internal
234  */
235 void QWebSocketPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
236 {
237     m_configuration.m_sslConfiguration = sslConfiguration;
238 }
239
240 /*!
241     \internal
242  */
243 QSslConfiguration QWebSocketPrivate::sslConfiguration() const
244 {
245     return m_configuration.m_sslConfiguration;
246 }
247
248 /*!
249     \internal
250  */
251 void QWebSocketPrivate::ignoreSslErrors(const QList<QSslError> &errors)
252 {
253     m_configuration.m_ignoredSslErrors = errors;
254 }
255
256 /*!
257  * \internal
258  */
259 void QWebSocketPrivate::ignoreSslErrors()
260 {
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();
266     }
267 }
268
269 #endif
270
271 /*!
272   Called from QWebSocketServer
273   \internal
274  */
275 QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
276                                            const QWebSocketHandshakeRequest &request,
277                                            const QWebSocketHandshakeResponse &response,
278                                            QObject *parent)
279 {
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);
289     }
290
291     return pWebSocket;
292 }
293
294 /*!
295     \internal
296  */
297 void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
298 {
299     if (Q_UNLIKELY(!m_pSocket))
300         return;
301     if (!m_isClosingHandshakeSent) {
302         Q_Q(QWebSocket);
303         const quint16 code = qToBigEndian<quint16>(closeCode);
304         QByteArray payload;
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;
309         if (m_mustMask) {
310             maskingKey = generateMaskingKey();
311             QWebSocketProtocol::mask(payload.data(), payload.size(), maskingKey);
312         }
313         QByteArray frame = getFrameHeader(QWebSocketProtocol::OpCodeClose,
314                                           payload.size(), maskingKey, true);
315         frame.append(payload);
316         m_pSocket->write(frame);
317         m_pSocket->flush();
318
319         m_isClosingHandshakeSent = true;
320
321         Q_EMIT q->aboutToClose();
322     }
323     m_pSocket->close();
324 }
325
326 /*!
327     \internal
328  */
329 void QWebSocketPrivate::open(const QUrl &url, bool mask)
330 {
331     //just delete the old socket for the moment;
332     //later, we can add more 'intelligent' handling by looking at the URL
333     //m_pSocket.reset();
334     Q_Q(QWebSocket);
335     if (!url.isValid() || url.toString().contains(QStringLiteral("\r\n"))) {
336         setErrorString(QWebSocket::tr("Invalid URL."));
337         Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
338         return;
339     }
340     QTcpSocket *pTcpSocket = m_pSocket.take();
341     if (pTcpSocket) {
342         releaseConnections(pTcpSocket);
343         pTcpSocket->deleteLater();
344     }
345     //if (m_url != url)
346     if (Q_LIKELY(!m_pSocket)) {
347         m_dataProcessor.clear();
348         m_isClosingHandshakeReceived = false;
349         m_isClosingHandshakeSent = false;
350
351         setRequestUrl(url);
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);
357             return;
358         }
359         if (!url.query().isEmpty()) {
360             if (!resourceName.endsWith(QChar::fromLatin1('?'))) {
361                 resourceName.append(QChar::fromLatin1('?'));
362             }
363             resourceName.append(url.query());
364         }
365         if (resourceName.isEmpty())
366             resourceName = QStringLiteral("/");
367         setResourceName(resourceName);
368         enableMasking(mask);
369
370     #ifndef QT_NO_SSL
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);
377             } else {
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);
385
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);
394
395                     sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
396                     if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors))
397                         sslSocket->ignoreSslErrors();
398                     else
399                         sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
400     #ifndef QT_NO_NETWORKPROXY
401                     sslSocket->setProxy(m_configuration.m_proxy);
402     #endif
403                     sslSocket->connectToHostEncrypted(url.host(), url.port(443));
404                 } else {
405                     const QString message = QWebSocket::tr("Out of memory.");
406                     setErrorString(message);
407                     Q_EMIT q->error(QAbstractSocket::SocketResourceError);
408                 }
409             }
410         } else
411     #endif
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);
419
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);
426     #endif
427                 m_pSocket->connectToHost(url.host(), url.port(80));
428             } else {
429                 const QString message = QWebSocket::tr("Out of memory.");
430                 setErrorString(message);
431                 Q_EMIT q->error(QAbstractSocket::SocketResourceError);
432             }
433         } else {
434             const QString message =
435                     QWebSocket::tr("Unsupported WebSocket scheme: %1").arg(url.scheme());
436             setErrorString(message);
437             Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
438         }
439     }
440 }
441
442 /*!
443     \internal
444  */
445 void QWebSocketPrivate::ping(const QByteArray &payload)
446 {
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);
453     Q_UNUSED(ret);
454 }
455
456 /*!
457   \internal
458     Sets the version to use for the WebSocket protocol;
459     this must be set before the socket is opened.
460 */
461 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
462 {
463     if (m_version != version)
464         m_version = version;
465 }
466
467 /*!
468     \internal
469     Sets the resource name of the connection; must be set before the socket is openend
470 */
471 void QWebSocketPrivate::setResourceName(const QString &resourceName)
472 {
473     if (m_resourceName != resourceName)
474         m_resourceName = resourceName;
475 }
476
477 /*!
478   \internal
479  */
480 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
481 {
482     if (m_requestUrl != requestUrl)
483         m_requestUrl = requestUrl;
484 }
485
486 /*!
487   \internal
488  */
489 void QWebSocketPrivate::setOrigin(const QString &origin)
490 {
491     if (m_origin != origin)
492         m_origin = origin;
493 }
494
495 /*!
496   \internal
497  */
498 void QWebSocketPrivate::setProtocol(const QString &protocol)
499 {
500     if (m_protocol != protocol)
501         m_protocol = protocol;
502 }
503
504 /*!
505   \internal
506  */
507 void QWebSocketPrivate::setExtension(const QString &extension)
508 {
509     if (m_extension != extension)
510         m_extension = extension;
511 }
512
513 /*!
514   \internal
515  */
516 void QWebSocketPrivate::enableMasking(bool enable)
517 {
518     if (m_mustMask != enable)
519         m_mustMask = enable;
520 }
521
522 /*!
523  * \internal
524  */
525 void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
526 {
527     Q_ASSERT(pTcpSocket);
528     Q_Q(QWebSocket);
529
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);
540 #endif
541         QObject::connect(pTcpSocket, &QAbstractSocket::readChannelFinished, q,
542                          &QWebSocket::readChannelFinished);
543         QObject::connect(pTcpSocket, &QAbstractSocket::aboutToClose, q, &QWebSocket::aboutToClose);
544
545         //catch signals
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);
552     }
553
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);
570 }
571
572 /*!
573  * \internal
574  */
575 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
576 {
577     if (Q_LIKELY(pTcpSocket))
578         pTcpSocket->disconnect(pTcpSocket);
579     m_dataProcessor.disconnect();
580 }
581
582 /*!
583     \internal
584  */
585 QWebSocketProtocol::Version QWebSocketPrivate::version() const
586 {
587     return m_version;
588 }
589
590 /*!
591     \internal
592  */
593 QString QWebSocketPrivate::resourceName() const
594 {
595     return m_resourceName;
596 }
597
598 /*!
599     \internal
600  */
601 QUrl QWebSocketPrivate::requestUrl() const
602 {
603     return m_requestUrl;
604 }
605
606 /*!
607     \internal
608  */
609 QString QWebSocketPrivate::origin() const
610 {
611     return m_origin;
612 }
613
614 /*!
615     \internal
616  */
617 QString QWebSocketPrivate::protocol() const
618 {
619     return m_protocol;
620 }
621
622 /*!
623     \internal
624  */
625 QString QWebSocketPrivate::extension() const
626 {
627     return m_extension;
628 }
629
630 /*!
631  * \internal
632  */
633 QWebSocketProtocol::CloseCode QWebSocketPrivate::closeCode() const
634 {
635     return m_closeCode;
636 }
637
638 /*!
639  * \internal
640  */
641 QString QWebSocketPrivate::closeReason() const
642 {
643     return m_closeReason;
644 }
645
646 /*!
647  * \internal
648  */
649 QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
650                                              quint64 payloadLength, quint32 maskingKey,
651                                              bool lastFrame)
652 {
653     QByteArray header;
654     quint8 byte = 0x00;
655     bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
656
657     if (Q_LIKELY(ok)) {
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));
661
662         byte = 0x00;
663         if (maskingKey != 0)
664             byte |= 0x80;
665         if (payloadLength <= 125) {
666             byte |= static_cast<quint8>(payloadLength);
667             header.append(static_cast<char>(byte));
668         } else if (payloadLength <= 0xFFFFU) {
669             byte |= 126;
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) {
674             byte |= 127;
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);
678         }
679
680         if (maskingKey != 0) {
681             const quint32 mask = qToBigEndian<quint32>(maskingKey);
682             header.append(static_cast<const char *>(static_cast<const void *>(&mask)),
683                           sizeof(quint32));
684         }
685     } else {
686         setErrorString(QStringLiteral("WebSocket::getHeader: payload too big!"));
687         Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
688     }
689
690     return header;
691 }
692
693 /*!
694  * \internal
695  */
696 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
697 {
698     qint64 payloadWritten = 0;
699     if (Q_UNLIKELY(!m_pSocket) || (state() != QAbstractSocket::ConnectedState))
700         return payloadWritten;
701
702     Q_Q(QWebSocket);
703     const QWebSocketProtocol::OpCode firstOpCode = isBinary ?
704                 QWebSocketProtocol::OpCodeBinary : QWebSocketProtocol::OpCodeText;
705
706     int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
707     QByteArray tmpData(data);
708     tmpData.detach();
709     char *payload = tmpData.data();
710     quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES;
711     if (Q_LIKELY(sizeLeft))
712         ++numFrames;
713
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))
717         numFrames = 1;
718     quint64 currentPosition = 0;
719     qint64 bytesWritten = 0;
720     quint64 bytesLeft = data.size();
721
722     for (int i = 0; i < numFrames; ++i) {
723         quint32 maskingKey = 0;
724         if (m_mustMask)
725             maskingKey = generateMaskingKey();
726
727         const bool isLastFrame = (i == (numFrames - 1));
728         const bool isFirstFrame = (i == 0);
729
730         const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
731         const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode
732                                                                : QWebSocketProtocol::OpCodeContinue;
733
734         //write header
735         bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
736
737         //write payload
738         if (Q_LIKELY(size > 0)) {
739             char *currentData = payload + currentPosition;
740             if (m_mustMask)
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;
746             } else {
747                 m_pSocket->flush();
748                 setErrorString(QWebSocket::tr("Error writing bytes to socket: %1.")
749                                .arg(m_pSocket->errorString()));
750                 Q_EMIT q->error(QAbstractSocket::NetworkError);
751                 break;
752             }
753         }
754         currentPosition += size;
755         bytesLeft -= size;
756     }
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);
761     }
762     return payloadWritten;
763 }
764
765 /*!
766     \internal
767  */
768 quint32 QWebSocketPrivate::generateMaskingKey() const
769 {
770     return m_pMaskGenerator->nextMask();
771 }
772
773 /*!
774     \internal
775  */
776 QByteArray QWebSocketPrivate::generateKey() const
777 {
778     QByteArray key;
779
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));
783     }
784
785     return key.toBase64();
786 }
787
788
789 /*!
790     \internal
791  */
792 QString QWebSocketPrivate::calculateAcceptKey(const QByteArray &key) const
793 {
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);
797 }
798
799 /*!
800     \internal
801  */
802 qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
803 {
804     qint64 written = 0;
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);
809     }
810     return written;
811 }
812
813 /*!
814     \internal
815  */
816 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
817 {
818     qint64 written = 0;
819     if (Q_LIKELY(m_pSocket))
820         written = m_pSocket->write(frame);
821     return written;
822 }
823
824 /*!
825     \internal
826  */
827 QString readLine(QTcpSocket *pSocket)
828 {
829     Q_ASSERT(pSocket);
830     QString line;
831     char c;
832     while (pSocket->getChar(&c)) {
833         if (c == char('\r')) {
834             pSocket->getChar(&c);
835             break;
836         } else {
837             line.append(QChar::fromLatin1(c));
838         }
839     }
840     return line;
841 }
842
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)
846 {
847     // from RFC 2616:
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
852
853     static const int minLength = 11;
854     static const int dotPos = 6;
855     static const int spacePos = 8;
856     static const char httpMagic[] = "HTTP/";
857
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
863         return false;
864     }
865
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';
869
870     int i = spacePos;
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);
873
874     bool ok;
875     *statusCode = code.toInt(&ok);
876     *reasonPhrase = QString::fromLatin1(status.constData() + j + 1);
877
878     return ok && uint(*majorVersion) <= 9 && uint(* minorVersion) <= 9;
879 }
880
881
882 //called on the client for a server handshake response
883 /*!
884     \internal
885  */
886 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
887 {
888     Q_Q(QWebSocket);
889     if (Q_UNLIKELY(!pSocket))
890         return;
891
892     bool ok = false;
893     QString errorDescription;
894
895     const QByteArray statusLine = pSocket->readLine();
896     int httpMajorVersion, httpMinorVersion;
897     int httpStatusCode;
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));
902     } else {
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]);
910             }
911             headerLine = readLine(pSocket);
912         }
913
914         const QString acceptKey = headers.value(QStringLiteral("sec-websocket-accept"),
915                                                 QString());
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"),
920 //                                                 QString());
921 //        const QString protocol = headers.value(QStringLiteral("sec-websocket-protocol"),
922 //                                               QString());
923         const QString version = headers.value(QStringLiteral("sec-websocket-version"),
924                                               QString());
925
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")));
933             if (ok) {
934                 const QString accept = calculateAcceptKey(m_key);
935                 ok = (accept == acceptKey);
936                 if (!ok)
937                     errorDescription =
938                       QWebSocket::tr("Accept-Key received from server %1 does not match the client key %2.")
939                             .arg(acceptKey).arg(accept);
940             } else {
941                 errorDescription =
942                     QWebSocket::tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.")
943                         .arg(QString::fromLatin1(statusLine));
944             }
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)
953                     errorDescription =
954                             QWebSocket::tr("Handshake: Server requests a version that we don't support: %1.")
955                             .arg(versions.join(QStringLiteral(", ")));
956                     ok = false;
957                 } else {
958                     //we tried v13, but something different went wrong
959                     errorDescription =
960                         QWebSocket::tr("QWebSocketPrivate::processHandshake: Unknown error condition encountered. Aborting connection.");
961                     ok = false;
962                 }
963             }
964         } else {
965             errorDescription =
966                     QWebSocket::tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).")
967                         .arg(httpStatusCode).arg(httpStatusMessage);
968             ok = false;
969         }
970
971         if (!ok) {
972             setErrorString(errorDescription);
973             Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
974         } else {
975             //handshake succeeded
976             setSocketState(QAbstractSocket::ConnectedState);
977             Q_EMIT q->connected();
978         }
979     }
980 }
981
982 /*!
983     \internal
984  */
985 void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState)
986 {
987     Q_ASSERT(m_pSocket);
988     Q_Q(QWebSocket);
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,
996                                            m_requestUrl.host()
997                                                 % QStringLiteral(":")
998                                                 % QString::number(m_requestUrl.port(80)),
999                                            origin(),
1000                                            QString(),
1001                                            QString(),
1002                                            m_key);
1003             if (handshake.isEmpty()) {
1004                 m_pSocket->abort();
1005                 Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
1006                 return;
1007             }
1008             m_pSocket->write(handshake.toLatin1());
1009         }
1010         break;
1011
1012     case QAbstractSocket::ClosingState:
1013         if (webSocketState == QAbstractSocket::ConnectedState)
1014             setSocketState(QAbstractSocket::ClosingState);
1015         break;
1016
1017     case QAbstractSocket::UnconnectedState:
1018         if (webSocketState != QAbstractSocket::UnconnectedState) {
1019             setSocketState(QAbstractSocket::UnconnectedState);
1020             Q_EMIT q->disconnected();
1021         }
1022         break;
1023
1024     case QAbstractSocket::HostLookupState:
1025     case QAbstractSocket::ConnectingState:
1026     case QAbstractSocket::BoundState:
1027     case QAbstractSocket::ListeningState:
1028         //do nothing
1029         //to make C++ compiler happy;
1030         break;
1031     default:
1032         break;
1033     }
1034 }
1035
1036 /*!
1037  \internal
1038  */
1039 void QWebSocketPrivate::processData()
1040 {
1041     Q_ASSERT(m_pSocket);
1042     while (m_pSocket->bytesAvailable()) {
1043         if (state() == QAbstractSocket::ConnectingState)
1044             processHandshake(m_pSocket.data());
1045         else
1046             m_dataProcessor.process(m_pSocket.data());
1047     }
1048 }
1049
1050 /*!
1051  \internal
1052  */
1053 void QWebSocketPrivate::processPing(const QByteArray &data)
1054 {
1055     Q_ASSERT(m_pSocket);
1056     quint32 maskingKey = 0;
1057     if (m_mustMask)
1058         maskingKey = generateMaskingKey();
1059     m_pSocket->write(getFrameHeader(QWebSocketProtocol::OpCodePong, data.size(), maskingKey, true));
1060     if (data.size() > 0) {
1061         QByteArray maskedData = data;
1062         if (m_mustMask)
1063             QWebSocketProtocol::mask(&maskedData, maskingKey);
1064         m_pSocket->write(maskedData);
1065     }
1066 }
1067
1068 /*!
1069  \internal
1070  */
1071 void QWebSocketPrivate::processPong(const QByteArray &data)
1072 {
1073     Q_Q(QWebSocket);
1074     Q_EMIT q->pong(static_cast<quint64>(m_pingTimer.elapsed()), data);
1075 }
1076
1077 /*!
1078  \internal
1079  */
1080 void QWebSocketPrivate::processClose(QWebSocketProtocol::CloseCode closeCode, QString closeReason)
1081 {
1082     m_isClosingHandshakeReceived = true;
1083     close(closeCode, closeReason);
1084 }
1085
1086 /*!
1087     \internal
1088  */
1089 QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
1090                                                   QString host,
1091                                                   QString origin,
1092                                                   QString extensions,
1093                                                   QString protocols,
1094                                                   QByteArray key)
1095 {
1096     QStringList handshakeRequest;
1097     if (resourceName.contains(QStringLiteral("\r\n"))) {
1098         setErrorString(QWebSocket::tr("The resource name contains newlines. " \
1099                                       "Possible attack detected."));
1100         return QString();
1101     }
1102     if (host.contains(QStringLiteral("\r\n"))) {
1103         setErrorString(QWebSocket::tr("The hostname contains newlines. " \
1104                                       "Possible attack detected."));
1105         return QString();
1106     }
1107     if (origin.contains(QStringLiteral("\r\n"))) {
1108         setErrorString(QWebSocket::tr("The origin contains newlines. " \
1109                                       "Possible attack detected."));
1110         return QString();
1111     }
1112     if (extensions.contains(QStringLiteral("\r\n"))) {
1113         setErrorString(QWebSocket::tr("The extensions attribute contains newlines. " \
1114                                       "Possible attack detected."));
1115         return QString();
1116     }
1117     if (protocols.contains(QStringLiteral("\r\n"))) {
1118         setErrorString(QWebSocket::tr("The protocols attribute contains newlines. " \
1119                                       "Possible attack detected."));
1120         return QString();
1121     }
1122
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");
1137
1138     return handshakeRequest.join(QStringLiteral("\r\n"));
1139 }
1140
1141 /*!
1142     \internal
1143  */
1144 QAbstractSocket::SocketState QWebSocketPrivate::state() const
1145 {
1146     return m_socketState;
1147 }
1148
1149 /*!
1150     \internal
1151  */
1152 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
1153 {
1154     Q_Q(QWebSocket);
1155     if (m_socketState != state) {
1156         m_socketState = state;
1157         Q_EMIT q->stateChanged(m_socketState);
1158     }
1159 }
1160
1161 /*!
1162     \internal
1163  */
1164 void QWebSocketPrivate::setErrorString(const QString &errorString)
1165 {
1166     if (m_errorString != errorString)
1167         m_errorString = errorString;
1168 }
1169
1170 /*!
1171     \internal
1172  */
1173 QHostAddress QWebSocketPrivate::localAddress() const
1174 {
1175     QHostAddress address;
1176     if (Q_LIKELY(m_pSocket))
1177         address = m_pSocket->localAddress();
1178     return address;
1179 }
1180
1181 /*!
1182     \internal
1183  */
1184 quint16 QWebSocketPrivate::localPort() const
1185 {
1186     quint16 port = 0;
1187     if (Q_LIKELY(m_pSocket))
1188         port = m_pSocket->localPort();
1189     return port;
1190 }
1191
1192 /*!
1193     \internal
1194  */
1195 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
1196 {
1197     return m_pauseMode;
1198 }
1199
1200 /*!
1201     \internal
1202  */
1203 QHostAddress QWebSocketPrivate::peerAddress() const
1204 {
1205     QHostAddress address;
1206     if (Q_LIKELY(m_pSocket))
1207         address = m_pSocket->peerAddress();
1208     return address;
1209 }
1210
1211 /*!
1212     \internal
1213  */
1214 QString QWebSocketPrivate::peerName() const
1215 {
1216     QString name;
1217     if (Q_LIKELY(m_pSocket))
1218         name = m_pSocket->peerName();
1219     return name;
1220 }
1221
1222 /*!
1223     \internal
1224  */
1225 quint16 QWebSocketPrivate::peerPort() const
1226 {
1227     quint16 port = 0;
1228     if (Q_LIKELY(m_pSocket))
1229         port = m_pSocket->peerPort();
1230     return port;
1231 }
1232
1233 #ifndef QT_NO_NETWORKPROXY
1234 /*!
1235     \internal
1236  */
1237 QNetworkProxy QWebSocketPrivate::proxy() const
1238 {
1239     return m_configuration.m_proxy;
1240 }
1241
1242 /*!
1243     \internal
1244  */
1245 void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
1246 {
1247     if (m_configuration.m_proxy != networkProxy)
1248         m_configuration.m_proxy = networkProxy;
1249 }
1250 #endif  //QT_NO_NETWORKPROXY
1251
1252 /*!
1253     \internal
1254  */
1255 void QWebSocketPrivate::setMaskGenerator(const QMaskGenerator *maskGenerator)
1256 {
1257     if (!maskGenerator)
1258         m_pMaskGenerator = &m_defaultMaskGenerator;
1259     else if (maskGenerator != m_pMaskGenerator)
1260         m_pMaskGenerator = const_cast<QMaskGenerator *>(maskGenerator);
1261 }
1262
1263 /*!
1264     \internal
1265  */
1266 const QMaskGenerator *QWebSocketPrivate::maskGenerator() const
1267 {
1268     Q_ASSERT(m_pMaskGenerator);
1269     return m_pMaskGenerator;
1270 }
1271
1272 /*!
1273     \internal
1274  */
1275 qint64 QWebSocketPrivate::readBufferSize() const
1276 {
1277     return m_readBufferSize;
1278 }
1279
1280 /*!
1281     \internal
1282  */
1283 void QWebSocketPrivate::resume()
1284 {
1285     if (Q_LIKELY(m_pSocket))
1286         m_pSocket->resume();
1287 }
1288
1289 /*!
1290   \internal
1291  */
1292 void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
1293 {
1294     m_pauseMode = pauseMode;
1295     if (Q_LIKELY(m_pSocket))
1296         m_pSocket->setPauseMode(m_pauseMode);
1297 }
1298
1299 /*!
1300     \internal
1301  */
1302 void QWebSocketPrivate::setReadBufferSize(qint64 size)
1303 {
1304     m_readBufferSize = size;
1305     if (Q_LIKELY(m_pSocket))
1306         m_pSocket->setReadBufferSize(m_readBufferSize);
1307 }
1308
1309 /*!
1310     \internal
1311  */
1312 bool QWebSocketPrivate::isValid() const
1313 {
1314     return (m_pSocket && m_pSocket->isValid() &&
1315             (m_socketState == QAbstractSocket::ConnectedState));
1316 }
1317
1318 QT_END_NAMESPACE