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, QWebSocketServerPrivate::SecureMode secureMode,
64 QWebSocketServer * const pWebSocketServer, QObject *parent) :
66 q_ptr(pWebSocketServer),
67 m_pTcpServer(Q_NULLPTR),
68 m_serverName(serverName),
69 m_secureMode(secureMode),
70 m_pendingConnections(),
71 m_error(QWebSocketProtocol::CC_NORMAL),
74 Q_ASSERT(pWebSocketServer);
75 if (m_secureMode == NON_SECURE_MODE) {
76 m_pTcpServer = new QTcpServer(this);
77 if (Q_LIKELY(m_pTcpServer)) {
78 connect(m_pTcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
80 qFatal("Could not allocate memory for tcp server.");
84 QSslServer *pSslServer = new QSslServer(this);
85 m_pTcpServer = pSslServer;
86 if (Q_LIKELY(m_pTcpServer)) {
87 connect(pSslServer, SIGNAL(newEncryptedConnection()), this, SLOT(onNewConnection()));
88 connect(pSslServer, SIGNAL(peerVerifyError(QSslError)), q_ptr, SIGNAL(peerVerifyError(QSslError)));
89 connect(pSslServer, SIGNAL(sslErrors(QList<QSslError>)), q_ptr, SIGNAL(sslErrors(QList<QSslError>)));
92 qFatal("SSL not supported on this platform.");
95 connect(m_pTcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), q_ptr, SIGNAL(acceptError(QAbstractSocket::SocketError)));
101 QWebSocketServerPrivate::~QWebSocketServerPrivate()
104 m_pTcpServer->deleteLater();
110 void QWebSocketServerPrivate::close()
112 Q_Q(QWebSocketServer);
113 m_pTcpServer->close();
114 while (!m_pendingConnections.isEmpty()) {
115 QWebSocket *pWebSocket = m_pendingConnections.dequeue();
116 pWebSocket->close(QWebSocketProtocol::CC_GOING_AWAY, tr("Server closed."));
117 pWebSocket->deleteLater();
119 //emit signal via the event queue, so the server gets time
120 //to process any hanging events, like flushing buffers aso
121 QMetaObject::invokeMethod(q, "closed", Qt::QueuedConnection);
127 QString QWebSocketServerPrivate::errorString() const
129 if (m_errorString.isEmpty()) {
130 return m_pTcpServer->errorString();
132 return m_errorString;
139 bool QWebSocketServerPrivate::hasPendingConnections() const
141 return !m_pendingConnections.isEmpty();
147 bool QWebSocketServerPrivate::isListening() const
149 return m_pTcpServer->isListening();
155 bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port)
157 return m_pTcpServer->listen(address, port);
163 int QWebSocketServerPrivate::maxPendingConnections() const
165 return m_pTcpServer->maxPendingConnections();
171 void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket)
173 if (m_pendingConnections.size() < maxPendingConnections()) {
174 m_pendingConnections.enqueue(pWebSocket);
181 QWebSocket *QWebSocketServerPrivate::nextPendingConnection()
183 QWebSocket *pWebSocket = Q_NULLPTR;
184 if (Q_LIKELY(!m_pendingConnections.isEmpty())) {
185 pWebSocket = m_pendingConnections.dequeue();
193 void QWebSocketServerPrivate::pauseAccepting()
195 m_pTcpServer->pauseAccepting();
198 #ifndef QT_NO_NETWORKPROXY
202 QNetworkProxy QWebSocketServerPrivate::proxy() const
204 return m_pTcpServer->proxy();
210 void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy)
212 m_pTcpServer->setProxy(networkProxy);
218 void QWebSocketServerPrivate::resumeAccepting()
220 m_pTcpServer->resumeAccepting();
226 QHostAddress QWebSocketServerPrivate::serverAddress() const
228 return m_pTcpServer->serverAddress();
234 QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const
242 quint16 QWebSocketServerPrivate::serverPort() const
244 return m_pTcpServer->serverPort();
250 void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections)
252 m_pTcpServer->setMaxPendingConnections(numConnections);
258 bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor)
260 return m_pTcpServer->setSocketDescriptor(socketDescriptor);
266 qintptr QWebSocketServerPrivate::socketDescriptor() const
268 return m_pTcpServer->socketDescriptor();
274 bool QWebSocketServerPrivate::waitForNewConnection(int msec, bool *timedOut)
276 return m_pTcpServer->waitForNewConnection(msec, timedOut);
282 QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const
284 QList<QWebSocketProtocol::Version> supportedVersions;
285 supportedVersions << QWebSocketProtocol::currentVersion(); //we only support V13
286 return supportedVersions;
292 QStringList QWebSocketServerPrivate::supportedProtocols() const
294 QStringList supportedProtocols;
295 return supportedProtocols; //no protocols are currently supported
301 QStringList QWebSocketServerPrivate::supportedExtensions() const
303 QStringList supportedExtensions;
304 return supportedExtensions; //no extensions are currently supported
310 void QWebSocketServerPrivate::setServerName(const QString &serverName)
312 if (m_serverName != serverName) {
313 m_serverName = serverName;
320 QString QWebSocketServerPrivate::serverName() const
328 QWebSocketServerPrivate::SecureMode QWebSocketServerPrivate::secureMode() const
334 void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
336 if (m_secureMode == SECURE_MODE) {
337 qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration);
339 qWarning() << tr("Cannot set SSL configuration for non-secure server.");
343 QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const
345 if (m_secureMode == SECURE_MODE) {
346 return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration();
348 return QSslConfiguration::defaultConfiguration();
353 void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, QString errorString)
355 if ((m_error != code) || (m_errorString != errorString)) {
356 Q_Q(QWebSocketServer);
358 m_errorString = errorString;
359 Q_EMIT q->serverError(code);
366 void QWebSocketServerPrivate::onNewConnection()
368 QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection();
369 connect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(handshakeReceived()));
375 void QWebSocketServerPrivate::onCloseConnection()
377 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(sender());
378 if (Q_LIKELY(pTcpSocket)) {
386 void QWebSocketServerPrivate::handshakeReceived()
388 Q_Q(QWebSocketServer);
389 QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(sender());
390 if (Q_LIKELY(pTcpSocket)) {
391 bool success = false;
392 bool isSecure = false;
394 disconnect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(handshakeReceived()));
396 QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
397 QTextStream textStream(pTcpSocket);
398 textStream >> request;
400 if (request.isValid()) {
401 QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
402 Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);
404 QWebSocketHandshakeResponse response(request,
406 corsAuthenticator.allowed(),
408 supportedProtocols(),
409 supportedExtensions());
411 if (response.isValid()) {
412 QTextStream httpStream(pTcpSocket);
413 httpStream << response;
416 if (response.canUpgrade()) {
417 QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket, request, response);
419 pWebSocket->setParent(this);
420 addPendingConnection(pWebSocket);
421 Q_EMIT q->newConnection();
424 setError(QWebSocketProtocol::CC_ABNORMAL_DISCONNECTION, tr("Upgrading to websocket failed."));
428 setError(response.error(), response.errorString());
431 setError(QWebSocketProtocol::CC_PROTOCOL_ERROR, tr("Invalid response received."));
435 qWarning() << tr("Closing socket because of invalid or unsupported request.");
439 qWarning() << tr("Sender socket is NULL. This should not happen, otherwise it is a Qt bug!!!");