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