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