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