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 QObject::connect(pSslServer, &QSslServer::peerVerifyError,
99 q_ptr, &QWebSocketServer::peerVerifyError);
100 QObject::connect(pSslServer, &QSslServer::sslErrors,
101 q_ptr, &QWebSocketServer::sslErrors);
104 qFatal("SSL not supported on this platform.");
107 QObject::connect(m_pTcpServer, &QTcpServer::acceptError, q_ptr, &QWebSocketServer::acceptError);
113 QWebSocketServerPrivate::~QWebSocketServerPrivate()
116 m_pTcpServer->deleteLater();
122 void QWebSocketServerPrivate::close(bool aboutToDestroy)
124 Q_Q(QWebSocketServer);
125 m_pTcpServer->close();
126 while (!m_pendingConnections.isEmpty()) {
127 QWebSocket *pWebSocket = m_pendingConnections.dequeue();
128 pWebSocket->close(QWebSocketProtocol::CloseCodeGoingAway,
129 QWebSocketServer::tr("Server closed."));
130 pWebSocket->deleteLater();
132 if (!aboutToDestroy) {
133 //emit signal via the event queue, so the server gets time
134 //to process any hanging events, like flushing buffers aso
135 QMetaObject::invokeMethod(q, "closed", Qt::QueuedConnection);
142 QString QWebSocketServerPrivate::errorString() const
144 if (m_errorString.isEmpty())
145 return m_pTcpServer->errorString();
147 return m_errorString;
153 bool QWebSocketServerPrivate::hasPendingConnections() const
155 return !m_pendingConnections.isEmpty();
161 bool QWebSocketServerPrivate::isListening() const
163 return m_pTcpServer->isListening();
169 bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port)
171 bool success = m_pTcpServer->listen(address, port);
173 setErrorFromSocketError(m_pTcpServer->serverError(), m_pTcpServer->errorString());
180 int QWebSocketServerPrivate::maxPendingConnections() const
182 return m_maxPendingConnections;
188 void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket)
190 if (m_pendingConnections.size() < maxPendingConnections())
191 m_pendingConnections.enqueue(pWebSocket);
197 void QWebSocketServerPrivate::setErrorFromSocketError(QAbstractSocket::SocketError error,
198 const QString &errorDescription)
201 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, errorDescription);
207 QWebSocket *QWebSocketServerPrivate::nextPendingConnection()
209 QWebSocket *pWebSocket = Q_NULLPTR;
210 if (Q_LIKELY(!m_pendingConnections.isEmpty()))
211 pWebSocket = m_pendingConnections.dequeue();
218 void QWebSocketServerPrivate::pauseAccepting()
220 m_pTcpServer->pauseAccepting();
223 #ifndef QT_NO_NETWORKPROXY
227 QNetworkProxy QWebSocketServerPrivate::proxy() const
229 return m_pTcpServer->proxy();
235 void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy)
237 m_pTcpServer->setProxy(networkProxy);
243 void QWebSocketServerPrivate::resumeAccepting()
245 m_pTcpServer->resumeAccepting();
251 QHostAddress QWebSocketServerPrivate::serverAddress() const
253 return m_pTcpServer->serverAddress();
259 QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const
267 quint16 QWebSocketServerPrivate::serverPort() const
269 return m_pTcpServer->serverPort();
275 void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections)
277 if (m_pTcpServer->maxPendingConnections() <= numConnections)
278 m_pTcpServer->setMaxPendingConnections(numConnections + 1);
279 m_maxPendingConnections = numConnections;
285 bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor)
287 return m_pTcpServer->setSocketDescriptor(socketDescriptor);
293 qintptr QWebSocketServerPrivate::socketDescriptor() const
295 return m_pTcpServer->socketDescriptor();
301 QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const
303 QList<QWebSocketProtocol::Version> supportedVersions;
304 supportedVersions << QWebSocketProtocol::currentVersion(); //we only support V13
305 return supportedVersions;
311 QStringList QWebSocketServerPrivate::supportedProtocols() const
313 QStringList supportedProtocols;
314 return supportedProtocols; //no protocols are currently supported
320 QStringList QWebSocketServerPrivate::supportedExtensions() const
322 QStringList supportedExtensions;
323 return supportedExtensions; //no extensions are currently supported
329 void QWebSocketServerPrivate::setServerName(const QString &serverName)
331 if (m_serverName != serverName)
332 m_serverName = serverName;
338 QString QWebSocketServerPrivate::serverName() const
346 QWebSocketServerPrivate::SslMode QWebSocketServerPrivate::secureMode() const
352 void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
354 if (m_secureMode == SecureMode)
355 qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration);
358 QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const
360 if (m_secureMode == SecureMode)
361 return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration();
363 return QSslConfiguration::defaultConfiguration();
367 void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, const QString &errorString)
369 if ((m_error != code) || (m_errorString != errorString)) {
370 Q_Q(QWebSocketServer);
372 m_errorString = errorString;
373 Q_EMIT q->serverError(code);
380 void QWebSocketServerPrivate::onNewConnection()
382 QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection();
383 //use a queued connection because a QSslSocket
384 //needs the event loop to process incoming data
385 //if not queued, data is incomplete when handshakeReceived is called
386 QObjectPrivate::connect(pTcpSocket, &QTcpSocket::readyRead,
387 this, &QWebSocketServerPrivate::handshakeReceived,
388 Qt::QueuedConnection);
394 void QWebSocketServerPrivate::onCloseConnection()
396 if (Q_LIKELY(currentSender)) {
397 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
398 if (Q_LIKELY(pTcpSocket))
406 void QWebSocketServerPrivate::handshakeReceived()
408 if (Q_UNLIKELY(!currentSender)) {
409 qWarning() << QWebSocketServer::tr("Sender is NULL. This is a Qt bug.");
412 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
413 if (Q_UNLIKELY(!pTcpSocket)) {
414 qWarning() << QWebSocketServer::tr("Sender is not a QTcpSocket. This is a Qt bug!!!");
417 Q_Q(QWebSocketServer);
418 bool success = false;
419 bool isSecure = false;
421 disconnect(pTcpSocket, &QTcpSocket::readyRead,
422 this, &QWebSocketServerPrivate::handshakeReceived);
424 if (m_pendingConnections.length() >= maxPendingConnections()) {
426 pTcpSocket->deleteLater();
427 qWarning() << QWebSocketServer::tr("Too many pending connections: " \
428 "New websocket connection not accepted.");
429 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
430 QWebSocketServer::tr("Too many pending connections."));
434 QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
435 QTextStream textStream(pTcpSocket);
436 request.readHandshake(textStream);
438 if (request.isValid()) {
439 QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
440 Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);
442 QWebSocketHandshakeResponse response(request,
444 corsAuthenticator.allowed(),
446 supportedProtocols(),
447 supportedExtensions());
449 if (response.isValid()) {
450 QTextStream httpStream(pTcpSocket);
451 httpStream << response;
454 if (response.canUpgrade()) {
455 QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
459 addPendingConnection(pWebSocket);
460 Q_EMIT q->newConnection();
463 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
464 QWebSocketServer::tr("Upgrading to websocket failed."));
468 setError(response.error(), response.errorString());
471 setError(QWebSocketProtocol::CloseCodeProtocolError,
472 QWebSocketServer::tr("Invalid response received."));
476 qWarning() << QWebSocketServer::tr("Closing socket because of invalid or unsupported request.");