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