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