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