de3d04d4959166119cad5061596f75747b95921e
[contrib/qtwebsockets.git] / src / websockets / qwebsocketserver_p.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
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 "qwebsocketserver.h"
43 #include "qwebsocketserver_p.h"
44 #ifndef QT_NO_SSL
45 #include "qsslserver_p.h"
46 #endif
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"
53
54 #include <QtNetwork/QTcpServer>
55 #include <QtNetwork/QTcpSocket>
56 #include <QtNetwork/QNetworkProxy>
57
58 QT_BEGIN_NAMESPACE
59
60 /*!
61     \internal
62  */
63 QWebSocketServerPrivate::QWebSocketServerPrivate(const QString &serverName,
64                                                  QWebSocketServerPrivate::SslMode secureMode,
65                                                  QWebSocketServer * const pWebSocketServer) :
66     QObjectPrivate(),
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),
73     m_errorString(),
74     m_maxPendingConnections(30)
75 {
76     Q_ASSERT(pWebSocketServer);
77 }
78
79 /*!
80     \internal
81  */
82 void QWebSocketServerPrivate::init()
83 {
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);
89         else
90             qFatal("Could not allocate memory for tcp server.");
91     } else {
92 #ifndef QT_NO_SSL
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);
103         }
104 #else
105         qFatal("SSL not supported on this platform.");
106 #endif
107     }
108     QObject::connect(m_pTcpServer, &QTcpServer::acceptError, q_ptr, &QWebSocketServer::acceptError);
109 }
110
111 /*!
112     \internal
113  */
114 QWebSocketServerPrivate::~QWebSocketServerPrivate()
115 {
116     close(true);
117     m_pTcpServer->deleteLater();
118 }
119
120 /*!
121     \internal
122  */
123 void QWebSocketServerPrivate::close(bool aboutToDestroy)
124 {
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();
132     }
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);
137     }
138 }
139
140 /*!
141     \internal
142  */
143 QString QWebSocketServerPrivate::errorString() const
144 {
145     if (m_errorString.isEmpty())
146         return m_pTcpServer->errorString();
147     else
148         return m_errorString;
149 }
150
151 /*!
152     \internal
153  */
154 bool QWebSocketServerPrivate::hasPendingConnections() const
155 {
156     return !m_pendingConnections.isEmpty();
157 }
158
159 /*!
160     \internal
161  */
162 bool QWebSocketServerPrivate::isListening() const
163 {
164     return m_pTcpServer->isListening();
165 }
166
167 /*!
168     \internal
169  */
170 bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port)
171 {
172     bool success = m_pTcpServer->listen(address, port);
173     if (!success)
174         setErrorFromSocketError(m_pTcpServer->serverError(), m_pTcpServer->errorString());
175     return success;
176 }
177
178 /*!
179     \internal
180  */
181 int QWebSocketServerPrivate::maxPendingConnections() const
182 {
183     return m_maxPendingConnections;
184 }
185
186 /*!
187     \internal
188  */
189 void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket)
190 {
191     if (m_pendingConnections.size() < maxPendingConnections())
192         m_pendingConnections.enqueue(pWebSocket);
193 }
194
195 /*!
196     \internal
197  */
198 void QWebSocketServerPrivate::setErrorFromSocketError(QAbstractSocket::SocketError error,
199                                                       const QString &errorDescription)
200 {
201     Q_UNUSED(error);
202     setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, errorDescription);
203 }
204
205 /*!
206     \internal
207  */
208 QWebSocket *QWebSocketServerPrivate::nextPendingConnection()
209 {
210     QWebSocket *pWebSocket = Q_NULLPTR;
211     if (Q_LIKELY(!m_pendingConnections.isEmpty()))
212         pWebSocket = m_pendingConnections.dequeue();
213     return pWebSocket;
214 }
215
216 /*!
217     \internal
218  */
219 void QWebSocketServerPrivate::pauseAccepting()
220 {
221     m_pTcpServer->pauseAccepting();
222 }
223
224 #ifndef QT_NO_NETWORKPROXY
225 /*!
226     \internal
227  */
228 QNetworkProxy QWebSocketServerPrivate::proxy() const
229 {
230     return m_pTcpServer->proxy();
231 }
232
233 /*!
234     \internal
235  */
236 void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy)
237 {
238     m_pTcpServer->setProxy(networkProxy);
239 }
240 #endif
241 /*!
242     \internal
243  */
244 void QWebSocketServerPrivate::resumeAccepting()
245 {
246     m_pTcpServer->resumeAccepting();
247 }
248
249 /*!
250     \internal
251  */
252 QHostAddress QWebSocketServerPrivate::serverAddress() const
253 {
254     return m_pTcpServer->serverAddress();
255 }
256
257 /*!
258     \internal
259  */
260 QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const
261 {
262     return m_error;
263 }
264
265 /*!
266     \internal
267  */
268 quint16 QWebSocketServerPrivate::serverPort() const
269 {
270     return m_pTcpServer->serverPort();
271 }
272
273 /*!
274     \internal
275  */
276 void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections)
277 {
278     if (m_pTcpServer->maxPendingConnections() <= numConnections)
279         m_pTcpServer->setMaxPendingConnections(numConnections + 1);
280     m_maxPendingConnections = numConnections;
281 }
282
283 /*!
284     \internal
285  */
286 bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor)
287 {
288     return m_pTcpServer->setSocketDescriptor(socketDescriptor);
289 }
290
291 /*!
292     \internal
293  */
294 qintptr QWebSocketServerPrivate::socketDescriptor() const
295 {
296     return m_pTcpServer->socketDescriptor();
297 }
298
299 /*!
300     \internal
301  */
302 QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const
303 {
304     QList<QWebSocketProtocol::Version> supportedVersions;
305     supportedVersions << QWebSocketProtocol::currentVersion();  //we only support V13
306     return supportedVersions;
307 }
308
309 /*!
310     \internal
311  */
312 QStringList QWebSocketServerPrivate::supportedProtocols() const
313 {
314     QStringList supportedProtocols;
315     return supportedProtocols;  //no protocols are currently supported
316 }
317
318 /*!
319     \internal
320  */
321 QStringList QWebSocketServerPrivate::supportedExtensions() const
322 {
323     QStringList supportedExtensions;
324     return supportedExtensions; //no extensions are currently supported
325 }
326
327 /*!
328   \internal
329  */
330 void QWebSocketServerPrivate::setServerName(const QString &serverName)
331 {
332     if (m_serverName != serverName)
333         m_serverName = serverName;
334 }
335
336 /*!
337   \internal
338  */
339 QString QWebSocketServerPrivate::serverName() const
340 {
341     return m_serverName;
342 }
343
344 /*!
345   \internal
346  */
347 QWebSocketServerPrivate::SslMode QWebSocketServerPrivate::secureMode() const
348 {
349     return m_secureMode;
350 }
351
352 #ifndef QT_NO_SSL
353 void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
354 {
355     if (m_secureMode == SecureMode)
356         qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration);
357 }
358
359 QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const
360 {
361     if (m_secureMode == SecureMode)
362         return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration();
363     else
364         return QSslConfiguration::defaultConfiguration();
365 }
366 #endif
367
368 void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, const QString &errorString)
369 {
370     if ((m_error != code) || (m_errorString != errorString)) {
371         Q_Q(QWebSocketServer);
372         m_error = code;
373         m_errorString = errorString;
374         Q_EMIT q->serverError(code);
375     }
376 }
377
378 /*!
379     \internal
380  */
381 void QWebSocketServerPrivate::onNewConnection()
382 {
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);
390 }
391
392 /*!
393     \internal
394  */
395 void QWebSocketServerPrivate::onCloseConnection()
396 {
397     if (Q_LIKELY(currentSender)) {
398         QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
399         if (Q_LIKELY(pTcpSocket))
400             pTcpSocket->close();
401     }
402 }
403
404 /*!
405     \internal
406  */
407 void QWebSocketServerPrivate::handshakeReceived()
408 {
409     if (Q_UNLIKELY(!currentSender)) {
410         qWarning() << QWebSocketServer::tr("Sender is NULL. This is a Qt bug.");
411         return;
412     }
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!!!");
416         return;
417     }
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()) {
426         return;
427     }
428     disconnect(pTcpSocket, &QTcpSocket::readyRead,
429                this, &QWebSocketServerPrivate::handshakeReceived);
430     Q_Q(QWebSocketServer);
431     bool success = false;
432     bool isSecure = false;
433
434     if (m_pendingConnections.length() >= maxPendingConnections()) {
435         pTcpSocket->close();
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."));
441         return;
442     }
443
444     QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
445     QTextStream textStream(pTcpSocket);
446     request.readHandshake(textStream);
447
448     if (request.isValid()) {
449         QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
450         Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);
451
452         QWebSocketHandshakeResponse response(request,
453                                              m_serverName,
454                                              corsAuthenticator.allowed(),
455                                              supportedVersions(),
456                                              supportedProtocols(),
457                                              supportedExtensions());
458
459         if (response.isValid()) {
460             QTextStream httpStream(pTcpSocket);
461             httpStream << response;
462             httpStream.flush();
463
464             if (response.canUpgrade()) {
465                 QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
466                                                                         request,
467                                                                         response);
468                 if (pWebSocket) {
469                     addPendingConnection(pWebSocket);
470                     Q_EMIT q->newConnection();
471                     success = true;
472                 } else {
473                     setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
474                              QWebSocketServer::tr("Upgrading to websocket failed."));
475                 }
476             }
477             else {
478                 setError(response.error(), response.errorString());
479             }
480         } else {
481             setError(QWebSocketProtocol::CloseCodeProtocolError,
482                      QWebSocketServer::tr("Invalid response received."));
483         }
484     }
485     if (!success) {
486         qWarning() << QWebSocketServer::tr("Closing socket because of invalid or unsupported request.");
487         pTcpSocket->close();
488     }
489 }
490
491 QT_END_NAMESPACE