10597d31008e28ba81bdc0278e8d892af4abfe3e
[contrib/qtwebsockets.git] / src / websockets / qwebsocket_p.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
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: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.
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 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.
24 **
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.
28 **
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.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qwebsocket.h"
43 #include "qwebsocket_p.h"
44 #include "qwebsocketprotocol_p.h"
45 #include "qwebsockethandshakerequest_p.h"
46 #include "qwebsockethandshakeresponse_p.h"
47
48 #include <QtCore/QUrl>
49 #include <QtNetwork/QAuthenticator>
50 #include <QtNetwork/QTcpSocket>
51 #include <QtCore/QByteArray>
52 #include <QtCore/QtEndian>
53 #include <QtCore/QCryptographicHash>
54 #include <QtCore/QRegularExpression>
55 #include <QtCore/QStringList>
56 #include <QtNetwork/QHostAddress>
57 #include <QtCore/QStringBuilder>   //for more efficient string concatenation
58 #ifndef QT_NONETWORKPROXY
59 #include <QtNetwork/QNetworkProxy>
60 #endif
61 #ifndef QT_NO_SSL
62 #include <QtNetwork/QSslConfiguration>
63 #include <QtNetwork/QSslError>
64 #endif
65
66 #include <QtCore/QDebug>
67
68 #include <limits>
69
70 QT_BEGIN_NAMESPACE
71
72 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2;      //maximum size of a frame when sending a message
73
74 QWebSocketConfiguration::QWebSocketConfiguration() :
75 #ifndef QT_NO_SSL
76     m_sslConfiguration(QSslConfiguration::defaultConfiguration()),
77     m_ignoredSslErrors(),
78     m_ignoreSslErrors(false),
79 #endif
80 #ifndef QT_NONETWORKPROXY
81     m_proxy(QNetworkProxy::DefaultProxy)
82 #endif
83 {
84 }
85
86 /*!
87     \internal
88 */
89 QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version,
90                                      QWebSocket *pWebSocket, QObject *parent) :
91     QObject(parent),
92     q_ptr(pWebSocket),
93     m_pSocket(),
94     m_errorString(QWebSocket::tr("Unknown error")),
95     m_version(version),
96     m_resourceName(),
97     m_requestUrl(),
98     m_origin(origin),
99     m_protocol(),
100     m_extension(),
101     m_socketState(QAbstractSocket::UnconnectedState),
102     m_pauseMode(QAbstractSocket::PauseNever),
103     m_readBufferSize(0),
104     m_key(),
105     m_mustMask(true),
106     m_isClosingHandshakeSent(false),
107     m_isClosingHandshakeReceived(false),
108     m_closeCode(QWebSocketProtocol::CloseCodeNormal),
109     m_closeReason(),
110     m_pingTimer(),
111     m_dataProcessor(),
112     m_configuration()
113 {
114     init();
115 }
116
117 /*!
118     \internal
119 */
120 QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version,
121                                      QWebSocket *pWebSocket, QObject *parent) :
122     QObject(parent),
123     q_ptr(pWebSocket),
124     m_pSocket(pTcpSocket),
125     m_errorString(pTcpSocket->errorString()),
126     m_version(version),
127     m_resourceName(),
128     m_requestUrl(),
129     m_origin(),
130     m_protocol(),
131     m_extension(),
132     m_socketState(pTcpSocket->state()),
133     m_pauseMode(pTcpSocket->pauseMode()),
134     m_readBufferSize(pTcpSocket->readBufferSize()),
135     m_key(),
136     m_mustMask(true),
137     m_isClosingHandshakeSent(false),
138     m_isClosingHandshakeReceived(false),
139     m_closeCode(QWebSocketProtocol::CloseCodeNormal),
140     m_closeReason(),
141     m_pingTimer(),
142     m_dataProcessor(),
143     m_configuration()
144 {
145     init();
146     makeConnections(m_pSocket.data());
147 }
148
149 /*!
150     \internal
151 */
152 void QWebSocketPrivate::init()
153 {
154     Q_ASSERT(q_ptr);
155     //TODO: need a better randomizer
156     qsrand(static_cast<uint>(QDateTime::currentMSecsSinceEpoch()));
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, 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     QTcpSocket *pTcpSocket = m_pSocket.take();
335     if (pTcpSocket) {
336         releaseConnections(pTcpSocket);
337         pTcpSocket->deleteLater();
338     }
339     //if (m_url != url)
340     if (Q_LIKELY(!m_pSocket)) {
341         Q_Q(QWebSocket);
342
343         m_dataProcessor.clear();
344         m_isClosingHandshakeReceived = false;
345         m_isClosingHandshakeSent = false;
346
347         setRequestUrl(url);
348         QString resourceName = url.path();
349         if (!url.query().isEmpty()) {
350             if (!resourceName.endsWith(QChar::fromLatin1('?'))) {
351                 resourceName.append(QChar::fromLatin1('?'));
352             }
353             resourceName.append(url.query());
354         }
355         if (resourceName.isEmpty())
356             resourceName = QStringLiteral("/");
357         setResourceName(resourceName);
358         enableMasking(mask);
359
360     #ifndef QT_NO_SSL
361         if (url.scheme() == QStringLiteral("wss")) {
362             if (!QSslSocket::supportsSsl()) {
363                 const QString message = tr("SSL Sockets are not supported on this platform.");
364                 setErrorString(message);
365                 Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
366             } else {
367                 QSslSocket *sslSocket = new QSslSocket(this);
368                 m_pSocket.reset(sslSocket);
369                 if (Q_LIKELY(m_pSocket)) {
370                     m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
371                     m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
372                     m_pSocket->setReadBufferSize(m_readBufferSize);
373                     m_pSocket->setPauseMode(m_pauseMode);
374
375                     makeConnections(m_pSocket.data());
376                     connect(sslSocket, &QSslSocket::encryptedBytesWritten, q,
377                             &QWebSocket::bytesWritten);
378                     setSocketState(QAbstractSocket::ConnectingState);
379
380                     sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
381                     if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors))
382                         sslSocket->ignoreSslErrors();
383                     else
384                         sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
385     #ifndef QT_NO_NETWORKPROXY
386                     sslSocket->setProxy(m_configuration.m_proxy);
387     #endif
388                     sslSocket->connectToHostEncrypted(url.host(), url.port(443));
389                 } else {
390                     const QString message = tr("Out of memory.");
391                     setErrorString(message);
392                     Q_EMIT q->error(QAbstractSocket::SocketResourceError);
393                 }
394             }
395         } else
396     #endif
397         if (url.scheme() == QStringLiteral("ws")) {
398             m_pSocket.reset(new QTcpSocket(this));
399             if (Q_LIKELY(m_pSocket)) {
400                 m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
401                 m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
402                 m_pSocket->setReadBufferSize(m_readBufferSize);
403                 m_pSocket->setPauseMode(m_pauseMode);
404
405                 makeConnections(m_pSocket.data());
406                 connect(m_pSocket.data(), &QAbstractSocket::bytesWritten, q,
407                         &QWebSocket::bytesWritten);
408                 setSocketState(QAbstractSocket::ConnectingState);
409     #ifndef QT_NO_NETWORKPROXY
410                 m_pSocket->setProxy(m_configuration.m_proxy);
411     #endif
412                 m_pSocket->connectToHost(url.host(), url.port(80));
413             } else {
414                 const QString message = tr("Out of memory.");
415                 setErrorString(message);
416                 Q_EMIT q->error(QAbstractSocket::SocketResourceError);
417             }
418         } else {
419             const QString message = tr("Unsupported websockets scheme: %1").arg(url.scheme());
420             setErrorString(message);
421             Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError);
422         }
423     }
424 }
425
426 /*!
427     \internal
428  */
429 void QWebSocketPrivate::ping(const QByteArray &payload)
430 {
431     QByteArray payloadTruncated = payload.left(125);
432     m_pingTimer.restart();
433     QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OpCodePing, payloadTruncated.size(),
434                                           0 /*do not mask*/, true);
435     pingFrame.append(payloadTruncated);
436     qint64 ret = writeFrame(pingFrame);
437     Q_UNUSED(ret);
438 }
439
440 /*!
441   \internal
442     Sets the version to use for the websocket protocol;
443     this must be set before the socket is opened.
444 */
445 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
446 {
447     if (m_version != version)
448         m_version = version;
449 }
450
451 /*!
452     \internal
453     Sets the resource name of the connection; must be set before the socket is openend
454 */
455 void QWebSocketPrivate::setResourceName(const QString &resourceName)
456 {
457     if (m_resourceName != resourceName)
458         m_resourceName = resourceName;
459 }
460
461 /*!
462   \internal
463  */
464 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
465 {
466     if (m_requestUrl != requestUrl)
467         m_requestUrl = requestUrl;
468 }
469
470 /*!
471   \internal
472  */
473 void QWebSocketPrivate::setOrigin(const QString &origin)
474 {
475     if (m_origin != origin)
476         m_origin = origin;
477 }
478
479 /*!
480   \internal
481  */
482 void QWebSocketPrivate::setProtocol(const QString &protocol)
483 {
484     if (m_protocol != protocol)
485         m_protocol = protocol;
486 }
487
488 /*!
489   \internal
490  */
491 void QWebSocketPrivate::setExtension(const QString &extension)
492 {
493     if (m_extension != extension)
494         m_extension = extension;
495 }
496
497 /*!
498   \internal
499  */
500 void QWebSocketPrivate::enableMasking(bool enable)
501 {
502     if (m_mustMask != enable)
503         m_mustMask = enable;
504 }
505
506 /*!
507  * \internal
508  */
509 void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
510 {
511     Q_ASSERT(pTcpSocket);
512     Q_Q(QWebSocket);
513
514     if (Q_LIKELY(pTcpSocket)) {
515         //pass through signals
516         typedef void (QAbstractSocket:: *ASErrorSignal)(QAbstractSocket::SocketError);
517         typedef void (QWebSocket:: *WSErrorSignal)(QAbstractSocket::SocketError);
518         connect(pTcpSocket,
519                 static_cast<ASErrorSignal>(&QAbstractSocket::error),
520                 q, static_cast<WSErrorSignal>(&QWebSocket::error));
521         connect(pTcpSocket, &QAbstractSocket::proxyAuthenticationRequired, q,
522                 &QWebSocket::proxyAuthenticationRequired);
523         connect(pTcpSocket, &QAbstractSocket::readChannelFinished, q,
524                 &QWebSocket::readChannelFinished);
525         connect(pTcpSocket, &QAbstractSocket::aboutToClose, q, &QWebSocket::aboutToClose);
526
527         //catch signals
528         connect(pTcpSocket, &QAbstractSocket::stateChanged, this,
529                 &QWebSocketPrivate::processStateChanged);
530         //!!!important to use a QueuedConnection here;
531         //with QTcpSocket there is no problem, but with QSslSocket the processing hangs
532         connect(pTcpSocket, &QAbstractSocket::readyRead, this,
533                 &QWebSocketPrivate::processData, Qt::QueuedConnection);
534     }
535
536     connect(&m_dataProcessor, &QWebSocketDataProcessor::textFrameReceived, q,
537             &QWebSocket::textFrameReceived);
538     connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryFrameReceived, q,
539             &QWebSocket::binaryFrameReceived);
540     connect(&m_dataProcessor, &QWebSocketDataProcessor::binaryMessageReceived, q,
541             &QWebSocket::binaryMessageReceived);
542     connect(&m_dataProcessor, &QWebSocketDataProcessor::textMessageReceived, q,
543             &QWebSocket::textMessageReceived);
544     connect(&m_dataProcessor, &QWebSocketDataProcessor::errorEncountered, this,
545             &QWebSocketPrivate::close);
546     connect(&m_dataProcessor, &QWebSocketDataProcessor::pingReceived, this,
547             &QWebSocketPrivate::processPing);
548     connect(&m_dataProcessor, &QWebSocketDataProcessor::pongReceived, this,
549             &QWebSocketPrivate::processPong);
550     connect(&m_dataProcessor, &QWebSocketDataProcessor::closeReceived, this,
551             &QWebSocketPrivate::processClose);
552 }
553
554 /*!
555  * \internal
556  */
557 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
558 {
559     if (Q_LIKELY(pTcpSocket))
560         disconnect(pTcpSocket);
561     disconnect(&m_dataProcessor);
562 }
563
564 /*!
565     \internal
566  */
567 QWebSocketProtocol::Version QWebSocketPrivate::version() const
568 {
569     return m_version;
570 }
571
572 /*!
573     \internal
574  */
575 QString QWebSocketPrivate::resourceName() const
576 {
577     return m_resourceName;
578 }
579
580 /*!
581     \internal
582  */
583 QUrl QWebSocketPrivate::requestUrl() const
584 {
585     return m_requestUrl;
586 }
587
588 /*!
589     \internal
590  */
591 QString QWebSocketPrivate::origin() const
592 {
593     return m_origin;
594 }
595
596 /*!
597     \internal
598  */
599 QString QWebSocketPrivate::protocol() const
600 {
601     return m_protocol;
602 }
603
604 /*!
605     \internal
606  */
607 QString QWebSocketPrivate::extension() const
608 {
609     return m_extension;
610 }
611
612 /*!
613  * \internal
614  */
615 QWebSocketProtocol::CloseCode QWebSocketPrivate::closeCode() const
616 {
617     return m_closeCode;
618 }
619
620 /*!
621  * \internal
622  */
623 QString QWebSocketPrivate::closeReason() const
624 {
625     return m_closeReason;
626 }
627
628 /*!
629  * \internal
630  */
631 QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
632                                              quint64 payloadLength, quint32 maskingKey,
633                                              bool lastFrame)
634 {
635     QByteArray header;
636     quint8 byte = 0x00;
637     bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
638
639     if (Q_LIKELY(ok)) {
640         //FIN, RSV1-3, opcode (RSV-1, RSV-2 and RSV-3 are zero)
641         byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00));
642         header.append(static_cast<char>(byte));
643
644         byte = 0x00;
645         if (maskingKey != 0)
646             byte |= 0x80;
647         if (payloadLength <= 125) {
648             byte |= static_cast<quint8>(payloadLength);
649             header.append(static_cast<char>(byte));
650         } else if (payloadLength <= 0xFFFFU) {
651             byte |= 126;
652             header.append(static_cast<char>(byte));
653             quint16 swapped = qToBigEndian<quint16>(static_cast<quint16>(payloadLength));
654             header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 2);
655         } else if (payloadLength <= 0x7FFFFFFFFFFFFFFFULL) {
656             byte |= 127;
657             header.append(static_cast<char>(byte));
658             quint64 swapped = qToBigEndian<quint64>(payloadLength);
659             header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 8);
660         }
661
662         if (maskingKey != 0) {
663             const quint32 mask = qToBigEndian<quint32>(maskingKey);
664             header.append(static_cast<const char *>(static_cast<const void *>(&mask)),
665                           sizeof(quint32));
666         }
667     } else {
668         setErrorString(QStringLiteral("WebSocket::getHeader: payload too big!"));
669         Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
670     }
671
672     return header;
673 }
674
675 /*!
676  * \internal
677  */
678 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
679 {
680     qint64 payloadWritten = 0;
681     if (Q_UNLIKELY(!m_pSocket) || (state() != QAbstractSocket::ConnectedState))
682         return payloadWritten;
683
684     Q_Q(QWebSocket);
685     const QWebSocketProtocol::OpCode firstOpCode = isBinary ?
686                 QWebSocketProtocol::OpCodeBinary : QWebSocketProtocol::OpCodeText;
687
688     int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
689     QByteArray tmpData(data);
690     tmpData.detach();
691     char *payload = tmpData.data();
692     quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES;
693     if (Q_LIKELY(sizeLeft))
694         ++numFrames;
695
696     //catch the case where the payload is zero bytes;
697     //in this case, we still need to send a frame
698     if (Q_UNLIKELY(numFrames == 0))
699         numFrames = 1;
700     quint64 currentPosition = 0;
701     qint64 bytesWritten = 0;
702     quint64 bytesLeft = data.size();
703
704     for (int i = 0; i < numFrames; ++i) {
705         quint32 maskingKey = 0;
706         if (m_mustMask)
707             maskingKey = generateMaskingKey();
708
709         const bool isLastFrame = (i == (numFrames - 1));
710         const bool isFirstFrame = (i == 0);
711
712         const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES);
713         const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode
714                                                                : QWebSocketProtocol::OpCodeContinue;
715
716         //write header
717         bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
718
719         //write payload
720         if (Q_LIKELY(size > 0)) {
721             char *currentData = payload + currentPosition;
722             if (m_mustMask)
723                 QWebSocketProtocol::mask(currentData, size, maskingKey);
724             qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
725             if (Q_LIKELY(written > 0)) {
726                 bytesWritten += written;
727                 payloadWritten += written;
728             } else {
729                 m_pSocket->flush();
730                 setErrorString(tr("Error writing bytes to socket: %1.")
731                                .arg(m_pSocket->errorString()));
732                 Q_EMIT q->error(QAbstractSocket::NetworkError);
733                 break;
734             }
735         }
736         currentPosition += size;
737         bytesLeft -= size;
738     }
739     if (Q_UNLIKELY(payloadWritten != data.size())) {
740         setErrorString(tr("Bytes written %1 != %2.").arg(payloadWritten).arg(data.size()));
741         Q_EMIT q->error(QAbstractSocket::NetworkError);
742     }
743     return payloadWritten;
744 }
745
746 /*!
747  * \internal
748  */
749 quint32 QWebSocketPrivate::generateRandomNumber() const
750 {
751     //TODO: need a better randomizer
752     return quint32((double(qrand()) / RAND_MAX) * std::numeric_limits<quint32>::max());
753 }
754
755 /*!
756     \internal
757  */
758 quint32 QWebSocketPrivate::generateMaskingKey() const
759 {
760     return generateRandomNumber();
761 }
762
763 /*!
764     \internal
765  */
766 QByteArray QWebSocketPrivate::generateKey() const
767 {
768     QByteArray key;
769
770     for (int i = 0; i < 4; ++i) {
771         const quint32 tmp = generateRandomNumber();
772         key.append(static_cast<const char *>(static_cast<const void *>(&tmp)), sizeof(quint32));
773     }
774
775     return key.toBase64();
776 }
777
778
779 /*!
780     \internal
781  */
782 QString QWebSocketPrivate::calculateAcceptKey(const QByteArray &key) const
783 {
784     const QByteArray tmpKey = key + QByteArrayLiteral("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
785     const QByteArray hash = QCryptographicHash::hash(tmpKey, QCryptographicHash::Sha1).toBase64();
786     return QString::fromLatin1(hash);
787 }
788
789 /*!
790     \internal
791  */
792 qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
793 {
794     qint64 written = 0;
795     if (Q_LIKELY(m_pSocket)) {
796         QList<QByteArray>::const_iterator it;
797         for (it = frames.cbegin(); it < frames.cend(); ++it)
798             written += writeFrame(*it);
799     }
800     return written;
801 }
802
803 /*!
804     \internal
805  */
806 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
807 {
808     qint64 written = 0;
809     if (Q_LIKELY(m_pSocket))
810         written = m_pSocket->write(frame);
811     return written;
812 }
813
814 /*!
815     \internal
816  */
817 QString readLine(QTcpSocket *pSocket)
818 {
819     Q_ASSERT(pSocket);
820     QString line;
821     char c;
822     while (pSocket->getChar(&c)) {
823         if (c == char('\r')) {
824             pSocket->getChar(&c);
825             break;
826         } else {
827             line.append(QChar::fromLatin1(c));
828         }
829     }
830     return line;
831 }
832
833 //called on the client for a server handshake response
834 /*!
835     \internal
836  */
837 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
838 {
839     Q_Q(QWebSocket);
840     if (Q_UNLIKELY(!pSocket))
841         return;
842
843     bool ok = false;
844     QString errorDescription;
845
846     const QString regExpStatusLine(QStringLiteral("^(HTTP/[0-9]+\\.[0-9]+)\\s([0-9]+)\\s(.*)"));
847     const QRegularExpression regExp(regExpStatusLine);
848     const QString statusLine = readLine(pSocket);
849     QString httpProtocol;
850     int httpStatusCode;
851     QString httpStatusMessage;
852     const QRegularExpressionMatch match = regExp.match(statusLine);
853     if (Q_LIKELY(match.hasMatch())) {
854         QStringList tokens = match.capturedTexts();
855         tokens.removeFirst();   //remove the search string
856         if (tokens.length() == 3) {
857             httpProtocol = tokens[0];
858             httpStatusCode = tokens[1].toInt();
859             httpStatusMessage = tokens[2].trimmed();
860             ok = true;
861         }
862     }
863     if (Q_UNLIKELY(!ok)) {
864         errorDescription = tr("Invalid statusline in response: %1.").arg(statusLine);
865     } else {
866         QString headerLine = readLine(pSocket);
867         QMap<QString, QString> headers;
868         while (!headerLine.isEmpty()) {
869             const QStringList headerField = headerLine.split(QStringLiteral(": "),
870                                                              QString::SkipEmptyParts);
871             headers.insertMulti(headerField[0], headerField[1]);
872             headerLine = readLine(pSocket);
873         }
874
875         const QString acceptKey = headers.value(QStringLiteral("Sec-WebSocket-Accept"),
876                                                 QString());
877         const QString upgrade = headers.value(QStringLiteral("Upgrade"), QString());
878         const QString connection = headers.value(QStringLiteral("Connection"), QString());
879 //        unused for the moment
880 //        const QString extensions = headers.value(QStringLiteral("Sec-WebSocket-Extensions"),
881 //                                                 QString());
882 //        const QString protocol = headers.value(QStringLiteral("Sec-WebSocket-Protocol"),
883 //                                               QString());
884         const QString version = headers.value(QStringLiteral("Sec-WebSocket-Version"),
885                                               QString());
886
887         if (Q_LIKELY(httpStatusCode == 101)) {
888             //HTTP/x.y 101 Switching Protocols
889             bool conversionOk = false;
890             const float version = httpProtocol.midRef(5).toFloat(&conversionOk);
891             //TODO: do not check the httpStatusText right now
892             ok = !(acceptKey.isEmpty() ||
893                    (!conversionOk || (version < 1.1f)) ||
894                    (upgrade.toLower() != QStringLiteral("websocket")) ||
895                    (connection.toLower() != QStringLiteral("upgrade")));
896             if (ok) {
897                 const QString accept = calculateAcceptKey(m_key);
898                 ok = (accept == acceptKey);
899                 if (!ok)
900                     errorDescription =
901                       tr("Accept-Key received from server %1 does not match the client key %2.")
902                             .arg(acceptKey).arg(accept);
903             } else {
904                 errorDescription =
905                     tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.")
906                         .arg(statusLine);
907             }
908         } else if (httpStatusCode == 400) {
909             //HTTP/1.1 400 Bad Request
910             if (!version.isEmpty()) {
911                 const QStringList versions = version.split(QStringLiteral(", "),
912                                                            QString::SkipEmptyParts);
913                 if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion()))) {
914                     //if needed to switch protocol version, then we are finished here
915                     //because we cannot handle other protocols than the RFC one (v13)
916                     errorDescription =
917                             tr("Handshake: Server requests a version that we don't support: %1.")
918                             .arg(versions.join(QStringLiteral(", ")));
919                     ok = false;
920                 } else {
921                     //we tried v13, but something different went wrong
922                     errorDescription =
923                         tr("QWebSocketPrivate::processHandshake: Unknown error condition " \
924                            "encountered. Aborting connection.");
925                     ok = false;
926                 }
927             }
928         } else {
929             errorDescription =
930                     tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).")
931                     .arg(httpStatusCode).arg(httpStatusMessage);
932             ok = false;
933         }
934
935         if (!ok) {
936             setErrorString(errorDescription);
937             Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
938         } else {
939             //handshake succeeded
940             setSocketState(QAbstractSocket::ConnectedState);
941             Q_EMIT q->connected();
942         }
943     }
944 }
945
946 /*!
947     \internal
948  */
949 void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState)
950 {
951     Q_ASSERT(m_pSocket);
952     Q_Q(QWebSocket);
953     QAbstractSocket::SocketState webSocketState = this->state();
954     switch (socketState) {
955     case QAbstractSocket::ConnectedState:
956         if (webSocketState == QAbstractSocket::ConnectingState) {
957             m_key = generateKey();
958             const QString handshake =
959                     createHandShakeRequest(m_resourceName,
960                                            m_requestUrl.host()
961                                                 % QStringLiteral(":")
962                                                 % QString::number(m_requestUrl.port(80)),
963                                            origin(),
964                                            QString(),
965                                            QString(),
966                                            m_key);
967             m_pSocket->write(handshake.toLatin1());
968         }
969         break;
970
971     case QAbstractSocket::ClosingState:
972         if (webSocketState == QAbstractSocket::ConnectedState)
973             setSocketState(QAbstractSocket::ClosingState);
974         break;
975
976     case QAbstractSocket::UnconnectedState:
977         if (webSocketState != QAbstractSocket::UnconnectedState) {
978             setSocketState(QAbstractSocket::UnconnectedState);
979             Q_EMIT q->disconnected();
980         }
981         break;
982
983     case QAbstractSocket::HostLookupState:
984     case QAbstractSocket::ConnectingState:
985     case QAbstractSocket::BoundState:
986     case QAbstractSocket::ListeningState:
987         //do nothing
988         //to make C++ compiler happy;
989         break;
990     default:
991         break;
992     }
993 }
994
995 /*!
996  \internal
997  */
998 void QWebSocketPrivate::processData()
999 {
1000     Q_ASSERT(m_pSocket);
1001     while (m_pSocket->bytesAvailable()) {
1002         if (state() == QAbstractSocket::ConnectingState)
1003             processHandshake(m_pSocket.data());
1004         else
1005             m_dataProcessor.process(m_pSocket.data());
1006     }
1007 }
1008
1009 /*!
1010  \internal
1011  */
1012 void QWebSocketPrivate::processPing(const QByteArray &data)
1013 {
1014     Q_ASSERT(m_pSocket);
1015     quint32 maskingKey = 0;
1016     if (m_mustMask)
1017         maskingKey = generateMaskingKey();
1018     m_pSocket->write(getFrameHeader(QWebSocketProtocol::OpCodePong, data.size(), maskingKey, true));
1019     if (data.size() > 0) {
1020         QByteArray maskedData = data;
1021         if (m_mustMask)
1022             QWebSocketProtocol::mask(&maskedData, maskingKey);
1023         m_pSocket->write(maskedData);
1024     }
1025 }
1026
1027 /*!
1028  \internal
1029  */
1030 void QWebSocketPrivate::processPong(const QByteArray &data)
1031 {
1032     Q_Q(QWebSocket);
1033     Q_EMIT q->pong(static_cast<quint64>(m_pingTimer.elapsed()), data);
1034 }
1035
1036 /*!
1037  \internal
1038  */
1039 void QWebSocketPrivate::processClose(QWebSocketProtocol::CloseCode closeCode, QString closeReason)
1040 {
1041     m_isClosingHandshakeReceived = true;
1042     close(closeCode, closeReason);
1043 }
1044
1045 /*!
1046     \internal
1047  */
1048 QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
1049                                                   QString host,
1050                                                   QString origin,
1051                                                   QString extensions,
1052                                                   QString protocols,
1053                                                   QByteArray key)
1054 {
1055     QStringList handshakeRequest;
1056
1057     handshakeRequest << QStringLiteral("GET ") % resourceName % QStringLiteral(" HTTP/1.1") <<
1058                         QStringLiteral("Host: ") % host <<
1059                         QStringLiteral("Upgrade: websocket") <<
1060                         QStringLiteral("Connection: Upgrade") <<
1061                         QStringLiteral("Sec-WebSocket-Key: ") % QString::fromLatin1(key);
1062     if (!origin.isEmpty())
1063         handshakeRequest << QStringLiteral("Origin: ") % origin;
1064     handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ")
1065                             % QString::number(QWebSocketProtocol::currentVersion());
1066     if (extensions.length() > 0)
1067         handshakeRequest << QStringLiteral("Sec-WebSocket-Extensions: ") % extensions;
1068     if (protocols.length() > 0)
1069         handshakeRequest << QStringLiteral("Sec-WebSocket-Protocol: ") % protocols;
1070     handshakeRequest << QStringLiteral("\r\n");
1071
1072     return handshakeRequest.join(QStringLiteral("\r\n"));
1073 }
1074
1075 /*!
1076     \internal
1077  */
1078 QAbstractSocket::SocketState QWebSocketPrivate::state() const
1079 {
1080     return m_socketState;
1081 }
1082
1083 /*!
1084     \internal
1085  */
1086 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
1087 {
1088     Q_Q(QWebSocket);
1089     if (m_socketState != state) {
1090         m_socketState = state;
1091         Q_EMIT q->stateChanged(m_socketState);
1092     }
1093 }
1094
1095 /*!
1096     \internal
1097  */
1098 void QWebSocketPrivate::setErrorString(const QString &errorString)
1099 {
1100     if (m_errorString != errorString)
1101         m_errorString = errorString;
1102 }
1103
1104 /*!
1105     \internal
1106  */
1107 QHostAddress QWebSocketPrivate::localAddress() const
1108 {
1109     QHostAddress address;
1110     if (Q_LIKELY(m_pSocket))
1111         address = m_pSocket->localAddress();
1112     return address;
1113 }
1114
1115 /*!
1116     \internal
1117  */
1118 quint16 QWebSocketPrivate::localPort() const
1119 {
1120     quint16 port = 0;
1121     if (Q_LIKELY(m_pSocket))
1122         port = m_pSocket->localPort();
1123     return port;
1124 }
1125
1126 /*!
1127     \internal
1128  */
1129 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
1130 {
1131     return m_pauseMode;
1132 }
1133
1134 /*!
1135     \internal
1136  */
1137 QHostAddress QWebSocketPrivate::peerAddress() const
1138 {
1139     QHostAddress address;
1140     if (Q_LIKELY(m_pSocket))
1141         address = m_pSocket->peerAddress();
1142     return address;
1143 }
1144
1145 /*!
1146     \internal
1147  */
1148 QString QWebSocketPrivate::peerName() const
1149 {
1150     QString name;
1151     if (Q_LIKELY(m_pSocket))
1152         name = m_pSocket->peerName();
1153     return name;
1154 }
1155
1156 /*!
1157     \internal
1158  */
1159 quint16 QWebSocketPrivate::peerPort() const
1160 {
1161     quint16 port = 0;
1162     if (Q_LIKELY(m_pSocket))
1163         port = m_pSocket->peerPort();
1164     return port;
1165 }
1166
1167 #ifndef QT_NO_NETWORKPROXY
1168 /*!
1169     \internal
1170  */
1171 QNetworkProxy QWebSocketPrivate::proxy() const
1172 {
1173     return m_configuration.m_proxy;
1174 }
1175
1176 /*!
1177     \internal
1178  */
1179 void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
1180 {
1181     if (networkProxy != networkProxy)
1182         m_configuration.m_proxy = networkProxy;
1183 }
1184 #endif  //QT_NO_NETWORKPROXY
1185
1186 /*!
1187     \internal
1188  */
1189 qint64 QWebSocketPrivate::readBufferSize() const
1190 {
1191     return m_readBufferSize;
1192 }
1193
1194 /*!
1195     \internal
1196  */
1197 void QWebSocketPrivate::resume()
1198 {
1199     if (Q_LIKELY(m_pSocket))
1200         m_pSocket->resume();
1201 }
1202
1203 /*!
1204   \internal
1205  */
1206 void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
1207 {
1208     m_pauseMode = pauseMode;
1209     if (Q_LIKELY(m_pSocket))
1210         m_pSocket->setPauseMode(m_pauseMode);
1211 }
1212
1213 /*!
1214     \internal
1215  */
1216 void QWebSocketPrivate::setReadBufferSize(qint64 size)
1217 {
1218     m_readBufferSize = size;
1219     if (Q_LIKELY(m_pSocket))
1220         m_pSocket->setReadBufferSize(m_readBufferSize);
1221 }
1222
1223 /*!
1224     \internal
1225  */
1226 bool QWebSocketPrivate::isValid() const
1227 {
1228     return (m_pSocket && m_pSocket->isValid() &&
1229             (m_socketState == QAbstractSocket::ConnectedState));
1230 }
1231
1232 QT_END_NAMESPACE