6c70d8ee4687e70cbcaf23dff1a6572d163cf700
[contrib/qtwebsockets.git] / src / websockets / qwebsocketserver.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:LGPL21$
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 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 **
26 ** In addition, as a special exception, Digia gives you certain additional
27 ** rights. These rights are described in the Digia Qt LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 **
30 ** $QT_END_LICENSE$
31 **
32 ****************************************************************************/
33
34 /*!
35     \class QWebSocketServer
36
37     \inmodule QtWebSockets
38
39     \brief Implements a WebSocket-based server.
40
41     It is modeled after QTcpServer, and behaves the same. So, if you know how to use QTcpServer,
42     you know how to use QWebSocketServer.
43     This class makes it possible to accept incoming WebSocket connections.
44     You can specify the port or have QWebSocketServer pick one automatically.
45     You can listen on a specific address or on all the machine's addresses.
46     Call listen() to have the server listen for incoming connections.
47
48     The newConnection() signal is then emitted each time a client connects to the server.
49     Call nextPendingConnection() to accept the pending connection as a connected QWebSocket.
50     The function returns a pointer to a QWebSocket in QAbstractSocket::ConnectedState that you can
51     use for communicating with the client.
52
53     If an error occurs, serverError() returns the type of error, and errorString() can be called
54     to get a human readable description of what happened.
55
56     When listening for connections, the address and port on which the server is listening are
57     available as serverAddress() and serverPort().
58
59     Calling close() makes QWebSocketServer stop listening for incoming connections.
60
61     QWebSocketServer currently does not support
62     \l {http://tools.ietf.org/html/rfc6455#page-39} {extensions} and
63     \l {http://tools.ietf.org/html/rfc6455#page-12} {subprotocols}.
64
65     \note When working with self-signed certificates, FireFox currently has a
66     \l {https://bugzilla.mozilla.org/show_bug.cgi?id=594502} {bug} that prevents it to
67     connect to a secure WebSocket server. To work around this problem, first browse to the
68     secure WebSocket server using HTTPS. FireFox will indicate that the certificate is invalid.
69     From here on, the certificate can be added to the exceptions. After this, the secure WebSockets
70     connection should work.
71
72     QWebSocketServer only supports version 13 of the WebSocket protocol, as outlined in RFC 6455.
73
74     \sa {WebSocket Server Example}, QWebSocket
75 */
76
77 /*!
78   \page echoserver.html example
79   \title WebSocket server example
80   \brief A sample WebSocket server echoing back messages sent to it.
81
82   \section1 Description
83   The echoserver example implements a WebSocket server that echoes back everything that is sent
84   to it.
85   \section1 Code
86   We start by creating a QWebSocketServer (`new QWebSocketServer()`). After the creation, we listen
87   on all local network interfaces (`QHostAddress::Any`) on the specified \a port.
88   \snippet echoserver/echoserver.cpp constructor
89   If listening is successful, we connect the `newConnection()` signal to the slot
90   `onNewConnection()`.
91   The `newConnection()` signal will be thrown whenever a new WebSocket client is connected to our
92   server.
93
94   \snippet echoserver/echoserver.cpp onNewConnection
95   When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`),
96   and the signals we are interested in are connected to our slots
97   (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
98   The client socket is remembered in a list, in case we would like to use it later
99   (in this example, nothing is done with it).
100
101   \snippet echoserver/echoserver.cpp processTextMessage
102   Whenever `processTextMessage()` is triggered, we retrieve the sender, and if valid, send back the
103   original message (`sendTextMessage()`).
104   The same is done with binary messages.
105   \snippet echoserver/echoserver.cpp processBinaryMessage
106   The only difference is that the message now is a QByteArray instead of a QString.
107
108   \snippet echoserver/echoserver.cpp socketDisconnected
109   Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
110   Note: it is best to use `deleteLater()` to delete the socket.
111 */
112
113 /*!
114     \fn void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
115     This signal is emitted when the acceptance of a new connection results in an error.
116     The \a socketError parameter describes the type of error that occurred.
117
118     \sa pauseAccepting(), resumeAccepting()
119 */
120
121 /*!
122     \fn void QWebSocketServer::serverError(QWebSocketProtocol::CloseCode closeCode)
123     This signal is emitted when an error occurs during the setup of a WebSocket connection.
124     The \a closeCode parameter describes the type of error that occurred
125
126     \sa errorString()
127 */
128
129 /*!
130     \fn void QWebSocketServer::newConnection()
131     This signal is emitted every time a new connection is available.
132
133     \sa hasPendingConnections(), nextPendingConnection()
134 */
135
136 /*!
137     \fn void QWebSocketServer::closed()
138     This signal is emitted when the server closed its connection.
139
140     \sa close()
141 */
142
143 /*!
144     \fn void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *authenticator)
145     This signal is emitted when a new connection is requested.
146     The slot connected to this signal should indicate whether the origin
147     (which can be determined by the origin() call) is allowed in the \a authenticator object
148     (by issuing \l{QWebSocketCorsAuthenticator::}{setAllowed()}).
149
150     If no slot is connected to this signal, all origins will be accepted by default.
151
152     \note It is not possible to use a QueuedConnection to connect to
153     this signal, as the connection will always succeed.
154 */
155
156 /*!
157     \fn void QWebSocketServer::peerVerifyError(const QSslError &error)
158
159     QWebSocketServer can emit this signal several times during the SSL handshake,
160     before encryption has been established, to indicate that an error has
161     occurred while establishing the identity of the peer. The \a error is
162     usually an indication that QWebSocketServer is unable to securely identify the
163     peer.
164
165     This signal provides you with an early indication when something is wrong.
166     By connecting to this signal, you can manually choose to tear down the
167     connection from inside the connected slot before the handshake has
168     completed. If no action is taken, QWebSocketServer will proceed to emitting
169     QWebSocketServer::sslErrors().
170
171     \sa sslErrors()
172 */
173
174 /*!
175     \fn void QWebSocketServer::sslErrors(const QList<QSslError> &errors)
176
177     QWebSocketServer emits this signal after the SSL handshake to indicate that one
178     or more errors have occurred while establishing the identity of the
179     peer. The errors are usually an indication that QWebSocketServer is unable to
180     securely identify the peer. Unless any action is taken, the connection
181     will be dropped after this signal has been emitted.
182
183     \a errors contains one or more errors that prevent QSslSocket from
184     verifying the identity of the peer.
185
186     \sa peerVerifyError()
187 */
188
189 /*!
190   \enum QWebSocketServer::SslMode
191   Indicates whether the server operates over wss (SecureMode) or ws (NonSecureMode)
192
193   \value SecureMode The server operates in secure mode (over wss)
194   \value NonSecureMode The server operates in non-secure mode (over ws)
195   */
196
197 #include "qwebsocketprotocol.h"
198 #include "qwebsocket.h"
199 #include "qwebsocketserver.h"
200 #include "qwebsocketserver_p.h"
201
202 #include <QtNetwork/QTcpServer>
203 #include <QtNetwork/QTcpSocket>
204 #include <QtNetwork/QNetworkProxy>
205
206 #ifndef QT_NO_SSL
207 #include <QtNetwork/QSslConfiguration>
208 #endif
209
210 QT_BEGIN_NAMESPACE
211
212 /*!
213     Constructs a new QWebSocketServer with the given \a serverName.
214     The \a serverName will be used in the HTTP handshake phase to identify the server.
215     It can be empty, in which case an empty server name will be sent to the client.
216     The \a secureMode parameter indicates whether the server operates over wss (\l{SecureMode})
217     or over ws (\l{NonSecureMode}).
218
219     \a parent is passed to the QObject constructor.
220  */
221 QWebSocketServer::QWebSocketServer(const QString &serverName, SslMode secureMode,
222                                    QObject *parent) :
223     QObject(*(new QWebSocketServerPrivate(serverName,
224                                       #ifndef QT_NO_SSL
225                                       (secureMode == SecureMode) ?
226                                           QWebSocketServerPrivate::SecureMode :
227                                           QWebSocketServerPrivate::NonSecureMode,
228                                       #else
229                                       QWebSocketServerPrivate::NonSecureMode,
230                                       #endif
231                                       this)), parent)
232 {
233 #ifdef QT_NO_SSL
234     Q_UNUSED(secureMode)
235 #endif
236     Q_D(QWebSocketServer);
237     d->init();
238 }
239
240 /*!
241     Destroys the QWebSocketServer object. If the server is listening for connections,
242     the socket is automatically closed.
243     Any client \l{QWebSocket}s that are still queued are closed and deleted.
244
245     \sa close()
246  */
247 QWebSocketServer::~QWebSocketServer()
248 {
249 }
250
251 /*!
252   Closes the server. The server will no longer listen for incoming connections.
253  */
254 void QWebSocketServer::close()
255 {
256     Q_D(QWebSocketServer);
257     d->close();
258 }
259
260 /*!
261     Returns a human readable description of the last error that occurred.
262     If no error occurred, an empty string is returned.
263
264     \sa serverError()
265 */
266 QString QWebSocketServer::errorString() const
267 {
268     Q_D(const QWebSocketServer);
269     return d->errorString();
270 }
271
272 /*!
273     Returns true if the server has pending connections; otherwise returns false.
274
275     \sa nextPendingConnection(), setMaxPendingConnections()
276  */
277 bool QWebSocketServer::hasPendingConnections() const
278 {
279     Q_D(const QWebSocketServer);
280     return d->hasPendingConnections();
281 }
282
283 /*!
284     Returns true if the server is currently listening for incoming connections;
285     otherwise returns false. If listening fails, error() will return the reason.
286
287     \sa listen(), error()
288  */
289 bool QWebSocketServer::isListening() const
290 {
291     Q_D(const QWebSocketServer);
292     return d->isListening();
293 }
294
295 /*!
296     Tells the server to listen for incoming connections on address \a address and port \a port.
297     If \a port is 0, a port is chosen automatically.
298     If \a address is QHostAddress::Any, the server will listen on all network interfaces.
299
300     Returns true on success; otherwise returns false.
301
302     \sa isListening()
303  */
304 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
305 {
306     Q_D(QWebSocketServer);
307     return d->listen(address, port);
308 }
309
310 /*!
311     Returns the maximum number of pending accepted connections. The default is 30.
312
313     \sa setMaxPendingConnections(), hasPendingConnections()
314  */
315 int QWebSocketServer::maxPendingConnections() const
316 {
317     Q_D(const QWebSocketServer);
318     return d->maxPendingConnections();
319 }
320
321 /*!
322     Returns the next pending connection as a connected QWebSocket object.
323     QWebSocketServer does not take ownership of the returned QWebSocket object.
324     It is up to the caller to delete the object explicitly when it will no longer be used,
325     otherwise a memory leak will occur.
326     Q_NULLPTR is returned if this function is called when there are no pending connections.
327
328     Note: The returned QWebSocket object cannot be used from another thread.
329
330     \sa hasPendingConnections()
331 */
332 QWebSocket *QWebSocketServer::nextPendingConnection()
333 {
334     Q_D(QWebSocketServer);
335     return d->nextPendingConnection();
336 }
337
338 /*!
339     Pauses incoming new connections. Queued connections will remain in queue.
340     \sa resumeAccepting()
341  */
342 void QWebSocketServer::pauseAccepting()
343 {
344     Q_D(QWebSocketServer);
345     d->pauseAccepting();
346 }
347
348 #ifndef QT_NO_NETWORKPROXY
349 /*!
350     Returns the network proxy for this server. By default QNetworkProxy::DefaultProxy is used.
351
352     \sa setProxy()
353 */
354 QNetworkProxy QWebSocketServer::proxy() const
355 {
356     Q_D(const QWebSocketServer);
357     return d->proxy();
358 }
359
360 /*!
361     Sets the explicit network proxy for this server to \a networkProxy.
362
363     To disable the use of a proxy, use the QNetworkProxy::NoProxy proxy type:
364
365     \code
366         server->setProxy(QNetworkProxy::NoProxy);
367     \endcode
368
369     \sa proxy()
370 */
371 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
372 {
373     Q_D(QWebSocketServer);
374     d->setProxy(networkProxy);
375 }
376 #endif
377
378 #ifndef QT_NO_SSL
379 /*!
380     Sets the SSL configuration for the QWebSocketServer to \a sslConfiguration.
381     This method has no effect if QWebSocketServer runs in non-secure mode
382     (QWebSocketServer::NonSecureMode).
383
384     \sa sslConfiguration(), SslMode
385  */
386 void QWebSocketServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
387 {
388     Q_D(QWebSocketServer);
389     d->setSslConfiguration(sslConfiguration);
390 }
391
392 /*!
393     Returns the SSL configuration used by the QWebSocketServer.
394     If the server is not running in secure mode (QWebSocketServer::SecureMode),
395     this method returns QSslConfiguration::defaultConfiguration().
396
397     \sa setSslConfiguration(), SslMode, QSslConfiguration::defaultConfiguration()
398  */
399 QSslConfiguration QWebSocketServer::sslConfiguration() const
400 {
401     Q_D(const QWebSocketServer);
402     return d->sslConfiguration();
403 }
404 #endif
405
406 /*!
407     Resumes accepting new connections.
408     \sa pauseAccepting()
409  */
410 void QWebSocketServer::resumeAccepting()
411 {
412     Q_D(QWebSocketServer);
413     d->resumeAccepting();
414 }
415
416 /*!
417     Sets the server name that will be used during the HTTP handshake phase to the given
418     \a serverName.
419     The \a serverName can be empty, in which case an empty server name will be sent to the client.
420     Existing connected clients will not be notified of this change, only newly connecting clients
421     will see this new name.
422  */
423 void QWebSocketServer::setServerName(const QString &serverName)
424 {
425     Q_D(QWebSocketServer);
426     d->setServerName(serverName);
427 }
428
429 /*!
430     Returns the server name that is used during the http handshake phase.
431  */
432 QString QWebSocketServer::serverName() const
433 {
434     Q_D(const QWebSocketServer);
435     return d->serverName();
436 }
437
438 /*!
439     Returns the server's address if the server is listening for connections; otherwise returns
440     QHostAddress::Null.
441
442     \sa serverPort(), listen()
443  */
444 QHostAddress QWebSocketServer::serverAddress() const
445 {
446     Q_D(const QWebSocketServer);
447     return d->serverAddress();
448 }
449
450 /*!
451     Returns the secure mode the server is running in.
452
453     \sa QWebSocketServer(), SslMode
454  */
455 QWebSocketServer::SslMode QWebSocketServer::secureMode() const
456 {
457 #ifndef QT_NO_SSL
458     Q_D(const QWebSocketServer);
459     return (d->secureMode() == QWebSocketServerPrivate::SecureMode) ?
460                 QWebSocketServer::SecureMode : QWebSocketServer::NonSecureMode;
461 #else
462     return QWebSocketServer::NonSecureMode;
463 #endif
464 }
465
466 /*!
467     Returns an error code for the last error that occurred.
468     If no error occurred, QWebSocketProtocol::CloseCodeNormal is returned.
469
470     \sa errorString()
471  */
472 QWebSocketProtocol::CloseCode QWebSocketServer::error() const
473 {
474     Q_D(const QWebSocketServer);
475     return d->serverError();
476 }
477
478 /*!
479     Returns the server's port if the server is listening for connections; otherwise returns 0.
480
481     \sa serverAddress(), listen()
482  */
483 quint16 QWebSocketServer::serverPort() const
484 {
485     Q_D(const QWebSocketServer);
486     return d->serverPort();
487 }
488
489 /*!
490     Returns a URL clients can use to connect to this server if the server is listening for connections.
491     Otherwise an invalid URL is returned.
492
493     \sa serverPort(), serverAddress(), listen()
494  */
495 QUrl QWebSocketServer::serverUrl() const
496 {
497     QUrl url;
498
499     if (!isListening()) {
500         return url;
501     }
502
503     switch (secureMode()) {
504     case NonSecureMode:
505         url.setScheme(QStringLiteral("ws"));
506         break;
507     #ifndef QT_NO_SSL
508     case SecureMode:
509         url.setScheme(QStringLiteral("wss"));
510         break;
511     #endif
512     }
513
514     url.setPort(serverPort());
515
516     if (serverAddress() == QHostAddress(QHostAddress::Any)) {
517         // NOTE: On Windows at least, clients cannot connect to QHostAddress::Any
518         // so in that case we always return LocalHost instead.
519         url.setHost(QHostAddress(QHostAddress::LocalHost).toString());
520     } else {
521         url.setHost(serverAddress().toString());
522     }
523
524     return url;
525 }
526
527 /*!
528     Sets the maximum number of pending accepted connections to \a numConnections.
529     WebSocketServer will accept no more than \a numConnections incoming connections before
530     nextPendingConnection() is called.
531     By default, the limit is 30 pending connections.
532
533     QWebSocketServer will emit the error() signal with
534     the QWebSocketProtocol::CloseCodeAbnormalDisconnection close code
535     when the maximum of connections has been reached.
536     The WebSocket handshake will fail and the socket will be closed.
537
538     \sa maxPendingConnections(), hasPendingConnections()
539  */
540 void QWebSocketServer::setMaxPendingConnections(int numConnections)
541 {
542     Q_D(QWebSocketServer);
543     d->setMaxPendingConnections(numConnections);
544 }
545
546 /*!
547     Sets the socket descriptor this server should use when listening for incoming connections to
548     \a socketDescriptor.
549
550     Returns true if the socket is set successfully; otherwise returns false.
551     The socket is assumed to be in listening state.
552
553     \sa socketDescriptor(), isListening()
554  */
555 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
556 {
557     Q_D(QWebSocketServer);
558     return d->setSocketDescriptor(socketDescriptor);
559 }
560
561 /*!
562     Returns the native socket descriptor the server uses to listen for incoming instructions,
563     or -1 if the server is not listening.
564     If the server is using QNetworkProxy, the returned descriptor may not be usable with
565     native socket functions.
566
567     \sa setSocketDescriptor(), isListening()
568  */
569 int QWebSocketServer::socketDescriptor() const
570 {
571     Q_D(const QWebSocketServer);
572     return d->socketDescriptor();
573 }
574
575 /*!
576   Returns a list of WebSocket versions that this server is supporting.
577  */
578 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
579 {
580     Q_D(const QWebSocketServer);
581     return d->supportedVersions();
582 }
583
584 QT_END_NAMESPACE