Add optimizations
[contrib/qtwebsockets.git] / src / websockets / qwebsocketserver_p.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
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, QWebSocketServerPrivate::SecureMode secureMode,
64                                                  QWebSocketServer * const pWebSocketServer, QObject *parent) :
65     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),
72     m_errorString()
73 {
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()));
79         } else {
80             qFatal("Could not allocate memory for tcp server.");
81         }
82     } else {
83 #ifndef QT_NO_SSL
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>)));
90         }
91 #else
92         qFatal("SSL not supported on this platform.");
93 #endif
94     }
95     connect(m_pTcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), q_ptr, SIGNAL(acceptError(QAbstractSocket::SocketError)));
96 }
97
98 /*!
99     \internal
100  */
101 QWebSocketServerPrivate::~QWebSocketServerPrivate()
102 {
103     close();
104     m_pTcpServer->deleteLater();
105 }
106
107 /*!
108     \internal
109  */
110 void QWebSocketServerPrivate::close()
111 {
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();
118     }
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);
122 }
123
124 /*!
125     \internal
126  */
127 QString QWebSocketServerPrivate::errorString() const
128 {
129     if (m_errorString.isEmpty()) {
130         return m_pTcpServer->errorString();
131     } else {
132         return m_errorString;
133     }
134 }
135
136 /*!
137     \internal
138  */
139 bool QWebSocketServerPrivate::hasPendingConnections() const
140 {
141     return !m_pendingConnections.isEmpty();
142 }
143
144 /*!
145     \internal
146  */
147 bool QWebSocketServerPrivate::isListening() const
148 {
149     return m_pTcpServer->isListening();
150 }
151
152 /*!
153     \internal
154  */
155 bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port)
156 {
157     return m_pTcpServer->listen(address, port);
158 }
159
160 /*!
161     \internal
162  */
163 int QWebSocketServerPrivate::maxPendingConnections() const
164 {
165     return m_pTcpServer->maxPendingConnections();
166 }
167
168 /*!
169     \internal
170  */
171 void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket)
172 {
173     if (m_pendingConnections.size() < maxPendingConnections()) {
174         m_pendingConnections.enqueue(pWebSocket);
175     }
176 }
177
178 /*!
179     \internal
180  */
181 QWebSocket *QWebSocketServerPrivate::nextPendingConnection()
182 {
183     QWebSocket *pWebSocket = Q_NULLPTR;
184     if (Q_LIKELY(!m_pendingConnections.isEmpty())) {
185         pWebSocket = m_pendingConnections.dequeue();
186     }
187     return pWebSocket;
188 }
189
190 /*!
191     \internal
192  */
193 void QWebSocketServerPrivate::pauseAccepting()
194 {
195     m_pTcpServer->pauseAccepting();
196 }
197
198 #ifndef QT_NO_NETWORKPROXY
199 /*!
200     \internal
201  */
202 QNetworkProxy QWebSocketServerPrivate::proxy() const
203 {
204     return m_pTcpServer->proxy();
205 }
206
207 /*!
208     \internal
209  */
210 void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy)
211 {
212     m_pTcpServer->setProxy(networkProxy);
213 }
214 #endif
215 /*!
216     \internal
217  */
218 void QWebSocketServerPrivate::resumeAccepting()
219 {
220     m_pTcpServer->resumeAccepting();
221 }
222
223 /*!
224     \internal
225  */
226 QHostAddress QWebSocketServerPrivate::serverAddress() const
227 {
228     return m_pTcpServer->serverAddress();
229 }
230
231 /*!
232     \internal
233  */
234 QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const
235 {
236     return m_error;
237 }
238
239 /*!
240     \internal
241  */
242 quint16 QWebSocketServerPrivate::serverPort() const
243 {
244     return m_pTcpServer->serverPort();
245 }
246
247 /*!
248     \internal
249  */
250 void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections)
251 {
252     m_pTcpServer->setMaxPendingConnections(numConnections);
253 }
254
255 /*!
256     \internal
257  */
258 bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor)
259 {
260     return m_pTcpServer->setSocketDescriptor(socketDescriptor);
261 }
262
263 /*!
264     \internal
265  */
266 qintptr QWebSocketServerPrivate::socketDescriptor() const
267 {
268     return m_pTcpServer->socketDescriptor();
269 }
270
271 /*!
272     \internal
273  */
274 bool QWebSocketServerPrivate::waitForNewConnection(int msec, bool *timedOut)
275 {
276     return m_pTcpServer->waitForNewConnection(msec, timedOut);
277 }
278
279 /*!
280     \internal
281  */
282 QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const
283 {
284     QList<QWebSocketProtocol::Version> supportedVersions;
285     supportedVersions << QWebSocketProtocol::currentVersion();  //we only support V13
286     return supportedVersions;
287 }
288
289 /*!
290     \internal
291  */
292 QStringList QWebSocketServerPrivate::supportedProtocols() const
293 {
294     QStringList supportedProtocols;
295     return supportedProtocols;  //no protocols are currently supported
296 }
297
298 /*!
299     \internal
300  */
301 QStringList QWebSocketServerPrivate::supportedExtensions() const
302 {
303     QStringList supportedExtensions;
304     return supportedExtensions; //no extensions are currently supported
305 }
306
307 /*!
308   \internal
309  */
310 void QWebSocketServerPrivate::setServerName(const QString &serverName)
311 {
312     if (m_serverName != serverName) {
313         m_serverName = serverName;
314     }
315 }
316
317 /*!
318   \internal
319  */
320 QString QWebSocketServerPrivate::serverName() const
321 {
322     return m_serverName;
323 }
324
325 /*!
326   \internal
327  */
328 QWebSocketServerPrivate::SecureMode QWebSocketServerPrivate::secureMode() const
329 {
330     return m_secureMode;
331 }
332
333 #ifndef QT_NO_SSL
334 void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
335 {
336     if (m_secureMode == SECURE_MODE) {
337         qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration);
338     } else {
339         qWarning() << tr("Cannot set SSL configuration for non-secure server.");
340     }
341 }
342
343 QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const
344 {
345     if (m_secureMode == SECURE_MODE) {
346         return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration();
347     } else {
348         return QSslConfiguration::defaultConfiguration();
349     }
350 }
351 #endif
352
353 void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, QString errorString)
354 {
355     if ((m_error != code) || (m_errorString != errorString)) {
356         Q_Q(QWebSocketServer);
357         m_error = code;
358         m_errorString = errorString;
359         Q_EMIT q->serverError(code);
360     }
361 }
362
363 /*!
364     \internal
365  */
366 void QWebSocketServerPrivate::onNewConnection()
367 {
368     QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection();
369     connect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(handshakeReceived()));
370 }
371
372 /*!
373     \internal
374  */
375 void QWebSocketServerPrivate::onCloseConnection()
376 {
377     QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(sender());
378     if (Q_LIKELY(pTcpSocket)) {
379         pTcpSocket->close();
380     }
381 }
382
383 /*!
384     \internal
385  */
386 void QWebSocketServerPrivate::handshakeReceived()
387 {
388     Q_Q(QWebSocketServer);
389     QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(sender());
390     if (Q_LIKELY(pTcpSocket)) {
391         bool success = false;
392         bool isSecure = false;
393
394         disconnect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(handshakeReceived()));
395
396         QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
397         QTextStream textStream(pTcpSocket);
398         textStream >> request;
399
400         if (request.isValid()) {
401             QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
402             Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);
403
404             QWebSocketHandshakeResponse response(request,
405                                                  m_serverName,
406                                                  corsAuthenticator.allowed(),
407                                                  supportedVersions(),
408                                                  supportedProtocols(),
409                                                  supportedExtensions());
410
411             if (response.isValid()) {
412                 QTextStream httpStream(pTcpSocket);
413                 httpStream << response;
414                 httpStream.flush();
415
416                 if (response.canUpgrade()) {
417                     QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket, request, response);
418                     if (pWebSocket) {
419                         pWebSocket->setParent(this);
420                         addPendingConnection(pWebSocket);
421                         Q_EMIT q->newConnection();
422                         success = true;
423                     } else {
424                         setError(QWebSocketProtocol::CC_ABNORMAL_DISCONNECTION, tr("Upgrading to websocket failed."));
425                     }
426                 }
427                 else {
428                     setError(response.error(), response.errorString());
429                 }
430             } else {
431                 setError(QWebSocketProtocol::CC_PROTOCOL_ERROR, tr("Invalid response received."));
432             }
433         }
434         if (!success) {
435             qWarning() << tr("Closing socket because of invalid or unsupported request.");
436             pTcpSocket->close();
437         }
438     } else {
439         qWarning() << tr("Sender socket is NULL. This should not happen, otherwise it is a Qt bug!!!");
440     }
441 }
442
443 QT_END_NAMESPACE