1 /****************************************************************************
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
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,
68 q_ptr(pWebSocketServer),
69 m_pTcpServer(Q_NULLPTR),
70 m_serverName(serverName),
71 m_secureMode(secureMode),
72 m_pendingConnections(),
73 m_error(QWebSocketProtocol::CloseCodeNormal),
76 Q_ASSERT(pWebSocketServer);
77 if (m_secureMode == NonSecureMode) {
78 m_pTcpServer = new QTcpServer(this);
79 if (Q_LIKELY(m_pTcpServer))
80 connect(m_pTcpServer, &QTcpServer::newConnection,
81 this, &QWebSocketServerPrivate::onNewConnection);
83 qFatal("Could not allocate memory for tcp server.");
86 QSslServer *pSslServer = new QSslServer(this);
87 m_pTcpServer = pSslServer;
88 if (Q_LIKELY(m_pTcpServer)) {
89 connect(pSslServer, &QSslServer::newEncryptedConnection,
90 this, &QWebSocketServerPrivate::onNewConnection);
91 connect(pSslServer, &QSslServer::peerVerifyError,
92 q_ptr, &QWebSocketServer::peerVerifyError);
93 connect(pSslServer, &QSslServer::sslErrors,
94 q_ptr, &QWebSocketServer::sslErrors);
97 qFatal("SSL not supported on this platform.");
100 connect(m_pTcpServer, &QTcpServer::acceptError, q_ptr, &QWebSocketServer::acceptError);
106 QWebSocketServerPrivate::~QWebSocketServerPrivate()
109 m_pTcpServer->deleteLater();
115 void QWebSocketServerPrivate::close()
117 Q_Q(QWebSocketServer);
118 m_pTcpServer->close();
119 while (!m_pendingConnections.isEmpty()) {
120 QWebSocket *pWebSocket = m_pendingConnections.dequeue();
121 pWebSocket->close(QWebSocketProtocol::CloseCodeGoingAway, tr("Server closed."));
122 pWebSocket->deleteLater();
124 //emit signal via the event queue, so the server gets time
125 //to process any hanging events, like flushing buffers aso
126 QMetaObject::invokeMethod(q, "closed", Qt::QueuedConnection);
132 QString QWebSocketServerPrivate::errorString() const
134 if (m_errorString.isEmpty())
135 return m_pTcpServer->errorString();
137 return m_errorString;
143 bool QWebSocketServerPrivate::hasPendingConnections() const
145 return !m_pendingConnections.isEmpty();
151 bool QWebSocketServerPrivate::isListening() const
153 return m_pTcpServer->isListening();
159 bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port)
161 bool success = m_pTcpServer->listen(address, port);
163 setErrorFromSocketError(m_pTcpServer->serverError(), m_pTcpServer->errorString());
170 int QWebSocketServerPrivate::maxPendingConnections() const
172 return m_pTcpServer->maxPendingConnections();
178 void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket)
180 if (m_pendingConnections.size() < maxPendingConnections())
181 m_pendingConnections.enqueue(pWebSocket);
187 void QWebSocketServerPrivate::setErrorFromSocketError(QAbstractSocket::SocketError error,
188 const QString &errorDescription)
191 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, errorDescription);
197 QWebSocket *QWebSocketServerPrivate::nextPendingConnection()
199 QWebSocket *pWebSocket = Q_NULLPTR;
200 if (Q_LIKELY(!m_pendingConnections.isEmpty()))
201 pWebSocket = m_pendingConnections.dequeue();
208 void QWebSocketServerPrivate::pauseAccepting()
210 m_pTcpServer->pauseAccepting();
213 #ifndef QT_NO_NETWORKPROXY
217 QNetworkProxy QWebSocketServerPrivate::proxy() const
219 return m_pTcpServer->proxy();
225 void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy)
227 m_pTcpServer->setProxy(networkProxy);
233 void QWebSocketServerPrivate::resumeAccepting()
235 m_pTcpServer->resumeAccepting();
241 QHostAddress QWebSocketServerPrivate::serverAddress() const
243 return m_pTcpServer->serverAddress();
249 QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const
257 quint16 QWebSocketServerPrivate::serverPort() const
259 return m_pTcpServer->serverPort();
265 void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections)
267 m_pTcpServer->setMaxPendingConnections(numConnections);
273 bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor)
275 return m_pTcpServer->setSocketDescriptor(socketDescriptor);
281 qintptr QWebSocketServerPrivate::socketDescriptor() const
283 return m_pTcpServer->socketDescriptor();
289 QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const
291 QList<QWebSocketProtocol::Version> supportedVersions;
292 supportedVersions << QWebSocketProtocol::currentVersion(); //we only support V13
293 return supportedVersions;
299 QStringList QWebSocketServerPrivate::supportedProtocols() const
301 QStringList supportedProtocols;
302 return supportedProtocols; //no protocols are currently supported
308 QStringList QWebSocketServerPrivate::supportedExtensions() const
310 QStringList supportedExtensions;
311 return supportedExtensions; //no extensions are currently supported
317 void QWebSocketServerPrivate::setServerName(const QString &serverName)
319 if (m_serverName != serverName)
320 m_serverName = serverName;
326 QString QWebSocketServerPrivate::serverName() const
334 QWebSocketServerPrivate::SslMode QWebSocketServerPrivate::secureMode() const
340 void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
342 if (m_secureMode == SecureMode)
343 qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration);
346 QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const
348 if (m_secureMode == SecureMode)
349 return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration();
351 return QSslConfiguration::defaultConfiguration();
355 void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, const QString &errorString)
357 if ((m_error != code) || (m_errorString != errorString)) {
358 Q_Q(QWebSocketServer);
360 m_errorString = errorString;
361 Q_EMIT q->serverError(code);
368 void QWebSocketServerPrivate::onNewConnection()
370 QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection();
371 connect(pTcpSocket, &QTcpSocket::readyRead, this, &QWebSocketServerPrivate::handshakeReceived);
377 void QWebSocketServerPrivate::onCloseConnection()
379 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(sender());
380 if (Q_LIKELY(pTcpSocket))
387 void QWebSocketServerPrivate::handshakeReceived()
389 Q_Q(QWebSocketServer);
390 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(sender());
391 if (Q_LIKELY(pTcpSocket)) {
392 bool success = false;
393 bool isSecure = false;
395 disconnect(pTcpSocket, &QTcpSocket::readyRead,
396 this, &QWebSocketServerPrivate::handshakeReceived);
398 if (m_pendingConnections.length() >= maxPendingConnections()) {
400 pTcpSocket->deleteLater();
401 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
402 tr("Too many pending connections."));
406 QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
407 QTextStream textStream(pTcpSocket);
408 request.readHandshake(textStream);
410 if (request.isValid()) {
411 QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
412 Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);
414 QWebSocketHandshakeResponse response(request,
416 corsAuthenticator.allowed(),
418 supportedProtocols(),
419 supportedExtensions());
421 if (response.isValid()) {
422 QTextStream httpStream(pTcpSocket);
423 httpStream << response;
426 if (response.canUpgrade()) {
427 QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
431 addPendingConnection(pWebSocket);
432 Q_EMIT q->newConnection();
435 setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
436 tr("Upgrading to websocket failed."));
440 setError(response.error(), response.errorString());
443 setError(QWebSocketProtocol::CloseCodeProtocolError, tr("Invalid response received."));
447 qWarning() << tr("Closing socket because of invalid or unsupported request.");
449 pTcpSocket->deleteLater();
453 tr("Sender socket is NULL. This should not happen, otherwise it is a Qt bug!!!");