Cleanup code to comply with Qt style
[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, you know how to use QWebSocketServer.
50     This class makes it possible to accept incoming websocket connections.
51     You can specify the port or have QWebSocketServer pick one automatically.
52     You can listen on a specific address or on all the machine's addresses.
53     Call listen() to have the server listen for incoming connections.
54
55     The newConnection() signal is then emitted each time a client connects to the server.
56     Call nextPendingConnection() to accept the pending connection as a connected QWebSocket.
57     The function returns a pointer to a QWebSocket in QAbstractSocket::ConnectedState that you can use for communicating with the client.
58     If an error occurs, serverError() returns the type of error, and errorString() can be called to get a human readable description of what happened.
59     When listening for connections, the address and port on which the server is listening are available as serverAddress() and serverPort().
60     Calling close() makes QWebSocketServer stop listening for incoming connections.
61     Although QWebSocketServer is mostly designed for use with an event loop, it's possible to use it without one. In that case, you must use waitForNewConnection(), which blocks until either a connection is available or a timeout expires.
62
63     \sa echoserver.html
64
65     \sa QWebSocket
66 */
67
68 /*!
69   \page echoserver.html example
70   \title WebSocket server example
71   \brief A sample websocket server echoing back messages sent to it.
72
73   \section1 Description
74   The echoserver example implements a web socket server that echoes back everything that is sent to it.
75   \section1 Code
76   We start by creating a QWebSocketServer (`new QWebSocketServer()`). After the creation, we listen on all local network interfaces (`QHostAddress::Any`) on the specified \a port.
77   \snippet echoserver/echoserver.cpp constructor
78   If listening is successful, we connect the `newConnection()` signal to the slot `onNewConnection()`.
79   The `newConnection()` signal will be thrown whenever a new web socket client is connected to our server.
80
81   \snippet echoserver/echoserver.cpp onNewConnection
82   When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`), and the signals we are interested in
83   are connected to our slots (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
84   The client socket is remembered in a list, in case we would like to use it later (in this example, nothing is done with it).
85
86   \snippet echoserver/echoserver.cpp processMessage
87   Whenever `processMessage()` is triggered, we retrieve the sender, and if valid, send back the original message (`send()`).
88   The same is done with binary messages.
89   \snippet echoserver/echoserver.cpp processBinaryMessage
90   The only difference is that the message now is a QByteArray instead of a QString.
91
92   \snippet echoserver/echoserver.cpp socketDisconnected
93   Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
94   Note: it is best to use `deleteLater()` to delete the socket.
95 */
96
97 /*!
98     \fn void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
99     This signal is emitted when accepting a new connection results in an error.
100     The \a socketError parameter describes the type of error that occurred
101
102     \sa pauseAccepting(), resumeAccepting()
103 */
104
105 /*!
106     \fn void QWebSocketServer::serverError(QNetworkProtocol::CloseCode closeCode)
107     This signal is emitted when an error occurs during the setup of a web socket connection.
108     The \a closeCode parameter describes the type of error that occurred
109
110     \sa errorString()
111 */
112
113 /*!
114     \fn void QWebSocketServer::newConnection()
115     This signal is emitted every time a new connection is available.
116
117     \sa hasPendingConnections(), nextPendingConnection()
118 */
119
120 /*!
121     \fn void QWebSocketServer::closed()
122     This signal is emitted when the server closed it's connection.
123
124     \sa close()
125 */
126
127 /*!
128     \fn void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *authenticator)
129     This signal is emitted when a new connection is requested.
130     The slot connected to this signal should indicate whether the origin (which can be determined by the origin() call)
131     is allowed in the \a authenticator object (by issuing \l{QWebSocketCorsAuthenticator::}{setAllowed()})
132
133     If no slot is connected to this signal, all origins will be accepted by default.
134
135     \note It is not possible to use a QueuedConnection to connect to
136     this signal, as the connection will always succeed.
137 */
138
139 #include "qwebsocketprotocol.h"
140 #include "qwebsocket.h"
141 #include "qwebsocketserver.h"
142 #include "qwebsocketserver_p.h"
143
144 #include <QtNetwork/QTcpServer>
145 #include <QtNetwork/QTcpSocket>
146 #include <QtNetwork/QNetworkProxy>
147
148 #ifndef QT_NO_SSL
149 #include <QtNetwork/QSslConfiguration>
150 #endif
151
152 QT_BEGIN_NAMESPACE
153
154 /*!
155     Constructs a new WebSocketServer with the given \a serverName.
156     The \a serverName will be used in the http handshake phase to identify the server.
157
158
159     \a parent is passed to the QObject constructor.
160  */
161 QWebSocketServer::QWebSocketServer(const QString &serverName, SecureMode secureMode, QObject *parent) :
162     QObject(parent),
163     d_ptr(new QWebSocketServerPrivate(serverName,
164                                       #ifndef QT_NO_SSL
165                                       (secureMode == SECURE_MODE) ? QWebSocketServerPrivate::SECURE_MODE : QWebSocketServerPrivate::NON_SECURE_MODE,
166                                       #else
167                                       QWebSocketServerPrivate::NON_SECURE_MODE,
168                                       #endif
169                                       this,
170                                       this))
171 {
172 #ifdef QT_NO_SSL
173     Q_UNUSED(secureMode)
174 #endif
175 }
176
177 /*!
178     Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
179     Any client WebSockets that are still connected are closed and deleted.
180
181     \sa close()
182  */
183 QWebSocketServer::~QWebSocketServer()
184 {
185     delete d_ptr;
186 }
187
188 /*!
189   Closes the server. The server will no longer listen for incoming connections.
190  */
191 void QWebSocketServer::close()
192 {
193     Q_D(QWebSocketServer);
194     d->close();
195 }
196
197 /*!
198     Returns a human readable description of the last error that occurred.
199
200     \sa serverError()
201 */
202 QString QWebSocketServer::errorString() const
203 {
204     Q_D(const QWebSocketServer);
205     return d->errorString();
206 }
207
208 /*!
209     Returns true if the server has pending connections; otherwise returns false.
210
211     \sa nextPendingConnection(), setMaxPendingConnections()
212  */
213 bool QWebSocketServer::hasPendingConnections() const
214 {
215     Q_D(const QWebSocketServer);
216     return d->hasPendingConnections();
217 }
218
219 /*!
220     Returns true if the server is currently listening for incoming connections; otherwise returns false.
221
222     \sa listen()
223  */
224 bool QWebSocketServer::isListening() const
225 {
226     Q_D(const QWebSocketServer);
227     return d->isListening();
228 }
229
230 /*!
231     Tells the server to listen for incoming connections on address \a address and port \a port.
232     If \a port is 0, a port is chosen automatically.
233     If \a address is QHostAddress::Any, the server will listen on all network interfaces.
234
235     Returns true on success; otherwise returns false.
236
237     \sa isListening()
238  */
239 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
240 {
241     Q_D(QWebSocketServer);
242     return d->listen(address, port);
243 }
244
245 /*!
246     Returns the maximum number of pending accepted connections. The default is 30.
247
248     \sa setMaxPendingConnections(), hasPendingConnections()
249  */
250 int QWebSocketServer::maxPendingConnections() const
251 {
252     Q_D(const QWebSocketServer);
253     return d->maxPendingConnections();
254 }
255
256 /*!
257     Returns the next pending connection as a connected WebSocket object.
258     The socket is created as a child of the server, which means that it is automatically deleted when the WebSocketServer object is destroyed. It is still a good idea to delete the object explicitly when you are done with it, to avoid wasting memory.
259     0 is returned if this function is called when there are no pending connections.
260
261     Note: The returned WebSocket object cannot be used from another thread..
262
263     \sa hasPendingConnections()
264 */
265 QWebSocket *QWebSocketServer::nextPendingConnection()
266 {
267     Q_D(QWebSocketServer);
268     return d->nextPendingConnection();
269 }
270
271 /*!
272     Pauses incoming new connections. Queued connections will remain in queue.
273     \sa resumeAccepting()
274  */
275 void QWebSocketServer::pauseAccepting()
276 {
277     Q_D(QWebSocketServer);
278     d->pauseAccepting();
279 }
280
281 #ifndef QT_NO_NETWORKPROXY
282 /*!
283     Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
284
285     \sa setProxy()
286 */
287 QNetworkProxy QWebSocketServer::proxy() const
288 {
289     Q_D(const QWebSocketServer);
290     return d->proxy();
291 }
292
293 /*!
294     \brief Sets the explicit network proxy for this socket to \a networkProxy.
295
296     To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
297
298     \code
299         server->setProxy(QNetworkProxy::NoProxy);
300     \endcode
301
302     \sa proxy()
303 */
304 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
305 {
306     Q_D(QWebSocketServer);
307     d->setProxy(networkProxy);
308 }
309 #endif
310
311 #ifndef QT_NO_SSL
312 /*!
313     Sets the SSL configuration for the websocket server to \a sslConfiguration.
314     This method has no effect if QWebSocketServer runs in non-secure mode (QWebSocketServer::NON_SECURE_MODE).
315
316     \sa sslConfiguration(), SecureMode
317  */
318 void QWebSocketServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
319 {
320     Q_D(QWebSocketServer);
321     d->setSslConfiguration(sslConfiguration);
322 }
323
324 /*!
325     Returns the SSL configuration used by the websocket server.
326     If the server is not running in secure mode (QWebSocketServer::SECURE_MODE),
327     this method returns QSslConfiguration::defaultConfiguration().
328
329     \sa sslConfiguration(), SecureMode, QSslConfiguration::defaultConfiguration()
330  */
331 QSslConfiguration QWebSocketServer::sslConfiguration() const
332 {
333     Q_D(const QWebSocketServer);
334     return d->sslConfiguration();
335 }
336 #endif
337
338 /*!
339     Resumes accepting new connections.
340     \sa pauseAccepting()
341  */
342 void QWebSocketServer::resumeAccepting()
343 {
344     Q_D(QWebSocketServer);
345     d->resumeAccepting();
346 }
347
348 /*!
349     Sets the server name that will be used during the http handshake phase to the given \a serverName.
350     Existing connected clients will not be notified of this change, only newly connecting clients
351     will see this new name.
352  */
353 void QWebSocketServer::setServerName(const QString &serverName)
354 {
355     Q_D(QWebSocketServer);
356     d->setServerName(serverName);
357 }
358
359 /*!
360     Returns the server name that is used during the http handshake phase.
361  */
362 QString QWebSocketServer::serverName() const
363 {
364     Q_D(const QWebSocketServer);
365     return d->serverName();
366 }
367
368 /*!
369     Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
370
371     \sa serverPort(), listen()
372  */
373 QHostAddress QWebSocketServer::serverAddress() const
374 {
375     Q_D(const QWebSocketServer);
376     return d->serverAddress();
377 }
378
379 /*!
380     Returns the mode the server is running in.
381
382     \sa QWebSocketServer(), SecureMode
383  */
384 QWebSocketServer::SecureMode QWebSocketServer::secureMode() const
385 {
386     Q_D(const QWebSocketServer);
387 #ifndef QT_NO_SSL
388     return (d->secureMode() == QWebSocketServerPrivate::SECURE_MODE) ?
389                 QWebSocketServer::SECURE_MODE : QWebSocketServer::NON_SECURE_MODE;
390 #else
391     return QWebSocketServer::NON_SECURE_MODE;
392 #endif
393 }
394
395 /*!
396     Returns an error code for the last error that occurred.
397     \sa errorString()
398  */
399 QWebSocketProtocol::CloseCode QWebSocketServer::error() const
400 {
401     Q_D(const QWebSocketServer);
402     return d->serverError();
403 }
404
405 /*!
406     Returns the server's port if the server is listening for connections; otherwise returns 0.
407     \sa serverAddress(), listen()
408  */
409 quint16 QWebSocketServer::serverPort() const
410 {
411     Q_D(const QWebSocketServer);
412     return d->serverPort();
413 }
414
415 /*!
416     Sets the maximum number of pending accepted connections to \a numConnections.
417     WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
418     By default, the limit is 30 pending connections.
419
420     Clients may still able to connect after the server has reached its maximum number of pending connections (i.e., WebSocket can still emit the connected() signal). WebSocketServer will stop accepting the new connections, but the operating system may still keep them in queue.
421     \sa maxPendingConnections(), hasPendingConnections()
422  */
423 void QWebSocketServer::setMaxPendingConnections(int numConnections)
424 {
425     Q_D(QWebSocketServer);
426     d->setMaxPendingConnections(numConnections);
427 }
428
429 /*!
430     Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
431
432     Returns true if the socket is set successfully; otherwise returns false.
433     The socket is assumed to be in listening state.
434
435     \sa socketDescriptor(), isListening()
436  */
437 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
438 {
439     Q_D(QWebSocketServer);
440     return d->setSocketDescriptor(socketDescriptor);
441 }
442
443 /*!
444     Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
445     If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
446
447     \sa setSocketDescriptor(), isListening()
448  */
449 int QWebSocketServer::socketDescriptor() const
450 {
451     Q_D(const QWebSocketServer);
452     return d->socketDescriptor();
453 }
454
455 /*!
456     Waits for at most \a msec milliseconds or until an incoming connection is available.
457     Returns true if a connection is available; otherwise returns false.
458     If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
459
460     \note This is a blocking function call.
461     \note Its use is disadvised in a single-threaded GUI application, since the whole application will stop responding until the function returns. waitForNewConnection() is mostly useful when there is no event loop available.
462     \note The non-blocking alternative is to connect to the newConnection() signal.
463
464     If \a msec is -1, this function will not time out.
465
466     \sa hasPendingConnections(), nextPendingConnection()
467 */
468 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
469 {
470     Q_D(QWebSocketServer);
471     return d->waitForNewConnection(msec, timedOut);
472 }
473
474 /*!
475   Returns a list of websocket versions that this server is supporting.
476  */
477 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
478 {
479     Q_D(const QWebSocketServer);
480     return d->supportedVersions();
481 }
482
483 /*!
484   Returns a list of websocket subprotocols that this server supports.
485  */
486 QStringList QWebSocketServer::supportedProtocols() const
487 {
488     Q_D(const QWebSocketServer);
489     return d->supportedProtocols();
490 }
491
492 /*!
493   Returns a list of websocket extensions that this server supports.
494  */
495 QStringList QWebSocketServer::supportedExtensions() const
496 {
497     Q_D(const QWebSocketServer);
498     return d->supportedExtensions();
499 }
500
501 QT_END_NAMESPACE