1 /****************************************************************************
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qwebsocketserver.h"
43 #include "qwebsocketserver_p.h"
45 #include "qsslserver_p.h"
47 #include "qwebsocketprotocol.h"
48 #include "qwebsockethandshakerequest_p.h"
49 #include "qwebsockethandshakeresponse_p.h"
50 #include "qwebsocket.h"
51 #include "qwebsocket_p.h"
52 #include "qwebsocketcorsauthenticator.h"
54 #include <QtNetwork/QTcpServer>
55 #include <QtNetwork/QTcpSocket>
56 #include <QtNetwork/QNetworkProxy>
63 QWebSocketServerPrivate::QWebSocketServerPrivate(const QString &serverName,
64 QWebSocketServerPrivate::SslMode secureMode,
65 QWebSocketServer * const pWebSocketServer) :
67 q_ptr(pWebSocketServer),
68 m_pTcpServer(Q_NULLPTR),
69 m_serverName(serverName),
70 m_secureMode(secureMode),
71 m_pendingConnections(),
72 m_error(QWebSocketProtocol::CloseCodeNormal),
74 m_maxPendingConnections(30)
76 Q_ASSERT(pWebSocketServer);
82 void QWebSocketServerPrivate::init()
84 if (m_secureMode == NonSecureMode) {
85 m_pTcpServer = new QTcpServer();
86 if (Q_LIKELY(m_pTcpServer))
87 QObjectPrivate::connect(m_pTcpServer, &QTcpServer::newConnection,
88 this, &QWebSocketServerPrivate::onNewConnection);
90 qFatal("Could not allocate memory for tcp server.");
93 QSslServer *pSslServer = new QSslServer();
94 m_pTcpServer = pSslServer;
95 if (Q_LIKELY(m_pTcpServer)) {
96 QObjectPrivate::connect(pSslServer, &QSslServer::newEncryptedConnection,
97 this, &QWebSocketServerPrivate::onNewConnection,
98 Qt::QueuedConnection);
99 QObject::connect(pSslServer, &QSslServer::peerVerifyError,
100 q_ptr, &QWebSocketServer::peerVerifyError);
101 QObject::connect(pSslServer, &QSslServer::sslErrors,
102 q_ptr, &QWebSocketServer::sslErrors);
105 qFatal("SSL not supported on this platform.");
108 QObject::connect(m_pTcpServer, &QTcpServer::acceptError, q_ptr, &QWebSocketServer::acceptError);
114 QWebSocketServerPrivate::~QWebSocketServerPrivate()
117 m_pTcpServer->deleteLater();
123 void QWebSocketServerPrivate::close(bool aboutToDestroy)
125 Q_Q(QWebSocketServer);
126 m_pTcpServer->close();
127 while (!m_pendingConnections.isEmpty()) {
128 QWebSocket *pWebSocket = m_pendingConnections.dequeue();
129 pWebSocket->close(QWebSocketProtocol::CloseCodeGoingAway,
130 QWebSocketServer::tr("Server closed."));
131 pWebSocket->deleteLater();
133 if (!aboutToDestroy) {
134 //emit signal via the event queue, so the server gets time
135 //to process any hanging events, like flushing buffers aso
136 QMetaObject::invokeMethod(q, "closed", Qt::QueuedConnection);
143 QString QWebSocketServerPrivate::errorString() const
145 if (m_errorString.isEmpty())
146 return m_pTcpServer->errorString();
148 return m_errorString;
154 bool QWebSocketServerPrivate::hasPendingConnections() const
156 return !m_pendingConnections.isEmpty();
162 bool QWebSocketServerPrivate::isListening() const
164 return m_pTcpServer->isListening();
170 bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port)
172 bool success = m_pTcpServer->listen(address, port);
174 setErrorFromSocketError(m_pTcpServer->serverError(), m_pTcpServer->errorString());
181 int QWebSocketServerPrivate::maxPendingConnections() const
183 return m_maxPendingConnections;
189 void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket)
191 if (m_pendingConnections.size() < maxPendingConnections())
192 m_pendingConnections.enqueue(pWebSocket);
198 void QWebSocketServerPrivate::setErrorFromSocketError(QAbstractSocket::SocketError error,
199 const QString &errorDescription)
202 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, errorDescription);
208 QWebSocket *QWebSocketServerPrivate::nextPendingConnection()
210 QWebSocket *pWebSocket = Q_NULLPTR;
211 if (Q_LIKELY(!m_pendingConnections.isEmpty()))
212 pWebSocket = m_pendingConnections.dequeue();
219 void QWebSocketServerPrivate::pauseAccepting()
221 m_pTcpServer->pauseAccepting();
224 #ifndef QT_NO_NETWORKPROXY
228 QNetworkProxy QWebSocketServerPrivate::proxy() const
230 return m_pTcpServer->proxy();
236 void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy)
238 m_pTcpServer->setProxy(networkProxy);
244 void QWebSocketServerPrivate::resumeAccepting()
246 m_pTcpServer->resumeAccepting();
252 QHostAddress QWebSocketServerPrivate::serverAddress() const
254 return m_pTcpServer->serverAddress();
260 QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const
268 quint16 QWebSocketServerPrivate::serverPort() const
270 return m_pTcpServer->serverPort();
276 void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections)
278 if (m_pTcpServer->maxPendingConnections() <= numConnections)
279 m_pTcpServer->setMaxPendingConnections(numConnections + 1);
280 m_maxPendingConnections = numConnections;
286 bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor)
288 return m_pTcpServer->setSocketDescriptor(socketDescriptor);
294 qintptr QWebSocketServerPrivate::socketDescriptor() const
296 return m_pTcpServer->socketDescriptor();
302 QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const
304 QList<QWebSocketProtocol::Version> supportedVersions;
305 supportedVersions << QWebSocketProtocol::currentVersion(); //we only support V13
306 return supportedVersions;
312 QStringList QWebSocketServerPrivate::supportedProtocols() const
314 QStringList supportedProtocols;
315 return supportedProtocols; //no protocols are currently supported
321 QStringList QWebSocketServerPrivate::supportedExtensions() const
323 QStringList supportedExtensions;
324 return supportedExtensions; //no extensions are currently supported
330 void QWebSocketServerPrivate::setServerName(const QString &serverName)
332 if (m_serverName != serverName)
333 m_serverName = serverName;
339 QString QWebSocketServerPrivate::serverName() const
347 QWebSocketServerPrivate::SslMode QWebSocketServerPrivate::secureMode() const
353 void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
355 if (m_secureMode == SecureMode)
356 qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration);
359 QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const
361 if (m_secureMode == SecureMode)
362 return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration();
364 return QSslConfiguration::defaultConfiguration();
368 void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, const QString &errorString)
370 if ((m_error != code) || (m_errorString != errorString)) {
371 Q_Q(QWebSocketServer);
373 m_errorString = errorString;
374 Q_EMIT q->serverError(code);
381 void QWebSocketServerPrivate::onNewConnection()
383 QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection();
384 //use a queued connection because a QSslSocket
385 //needs the event loop to process incoming data
386 //if not queued, data is incomplete when handshakeReceived is called
387 QObjectPrivate::connect(pTcpSocket, &QTcpSocket::readyRead,
388 this, &QWebSocketServerPrivate::handshakeReceived,
389 Qt::QueuedConnection);
395 void QWebSocketServerPrivate::onCloseConnection()
397 if (Q_LIKELY(currentSender)) {
398 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
399 if (Q_LIKELY(pTcpSocket))
407 void QWebSocketServerPrivate::handshakeReceived()
409 if (Q_UNLIKELY(!currentSender)) {
410 qWarning() << QWebSocketServer::tr("Sender is NULL. This is a Qt bug.");
413 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
414 if (Q_UNLIKELY(!pTcpSocket)) {
415 qWarning() << QWebSocketServer::tr("Sender is not a QTcpSocket. This is a Qt bug!!!");
418 //When using Google Chrome the handshake in received in two parts.
419 //Therefore, the readyRead signal is emitted twice.
420 //This is a guard against the BEAST attack.
421 //See: https://www.imperialviolet.org/2012/01/15/beastfollowup.html
422 //For Safari, the handshake is delivered at once
423 //FIXME: For FireFox, the readyRead signal is never emitted
424 //This is a bug in FireFox (see https://bugzilla.mozilla.org/show_bug.cgi?id=594502)
425 if (!pTcpSocket->canReadLine()) {
428 disconnect(pTcpSocket, &QTcpSocket::readyRead,
429 this, &QWebSocketServerPrivate::handshakeReceived);
430 Q_Q(QWebSocketServer);
431 bool success = false;
432 bool isSecure = false;
434 if (m_pendingConnections.length() >= maxPendingConnections()) {
436 pTcpSocket->deleteLater();
437 qWarning() << QWebSocketServer::tr("Too many pending connections: " \
438 "New WebSocket connection not accepted.");
439 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
440 QWebSocketServer::tr("Too many pending connections."));
444 QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
445 QTextStream textStream(pTcpSocket);
446 request.readHandshake(textStream);
448 if (request.isValid()) {
449 QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
450 Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);
452 QWebSocketHandshakeResponse response(request,
454 corsAuthenticator.allowed(),
456 supportedProtocols(),
457 supportedExtensions());
459 if (response.isValid()) {
460 QTextStream httpStream(pTcpSocket);
461 httpStream << response;
464 if (response.canUpgrade()) {
465 QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
469 addPendingConnection(pWebSocket);
470 Q_EMIT q->newConnection();
473 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
474 QWebSocketServer::tr("Upgrade to WebSocket failed."));
478 setError(response.error(), response.errorString());
481 setError(QWebSocketProtocol::CloseCodeProtocolError,
482 QWebSocketServer::tr("Invalid response received."));
486 qWarning() << QWebSocketServer::tr("Closing socket because of invalid or unsupported request.");