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