Sanitize include directives
[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::newConnection()
107     This signal is emitted every time a new connection is available.
108
109     \sa hasPendingConnections(), nextPendingConnection()
110 */
111
112 /*!
113     \fn void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *authenticator)
114     This signal is emitted when a new connection is requested.
115     The slot connected to this signal should indicate whether the origin (which can be determined by the origin() call)
116     is allowed in the \a authenticator object (by issuing \l{QWebSocketCorsAuthenticator::}{setAllowed()})
117
118     If no slot is connected to this signal, all origins will be accepted by default.
119
120     \note It is not possible to use a QueuedConnection to connect to
121     this signal, as the connection will always succeed.
122 */
123
124 #include "qwebsocketprotocol.h"
125 #include "qwebsocket.h"
126 #include "qwebsocketserver.h"
127 #include "qwebsocketserver_p.h"
128
129 #include <QtNetwork/QTcpServer>
130 #include <QtNetwork/QTcpSocket>
131 #include <QtNetwork/QNetworkProxy>
132
133 QT_BEGIN_NAMESPACE
134
135 /*!
136     Constructs a new WebSocketServer with the given \a serverName.
137     The \a serverName will be used in the http handshake phase to identify the server.
138
139     \a parent is passed to the QObject constructor.
140  */
141 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
142     QObject(parent),
143     d_ptr(new QWebSocketServerPrivate(serverName, this, this))
144 {
145 }
146
147 /*!
148     Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
149     Any client WebSockets that are still connected are closed and deleted.
150
151     \sa close()
152  */
153 QWebSocketServer::~QWebSocketServer()
154 {
155     delete d_ptr;
156 }
157
158 /*!
159   Closes the server. The server will no longer listen for incoming connections.
160  */
161 void QWebSocketServer::close()
162 {
163     Q_D(QWebSocketServer);
164     d->close();
165 }
166
167 /*!
168     Returns a human readable description of the last error that occurred.
169
170     \sa serverError()
171 */
172 QString QWebSocketServer::errorString() const
173 {
174     Q_D(const QWebSocketServer);
175     return d->errorString();
176 }
177
178 /*!
179     Returns true if the server has pending connections; otherwise returns false.
180
181     \sa nextPendingConnection(), setMaxPendingConnections()
182  */
183 bool QWebSocketServer::hasPendingConnections() const
184 {
185     Q_D(const QWebSocketServer);
186     return d->hasPendingConnections();
187 }
188
189 /*!
190     Returns true if the server is currently listening for incoming connections; otherwise returns false.
191
192     \sa listen()
193  */
194 bool QWebSocketServer::isListening() const
195 {
196     Q_D(const QWebSocketServer);
197     return d->isListening();
198 }
199
200 /*!
201     Tells the server to listen for incoming connections on address \a address and port \a port.
202     If \a port is 0, a port is chosen automatically.
203     If \a address is QHostAddress::Any, the server will listen on all network interfaces.
204
205     Returns true on success; otherwise returns false.
206
207     \sa isListening()
208  */
209 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
210 {
211     Q_D(QWebSocketServer);
212     return d->listen(address, port);
213 }
214
215 /*!
216     Returns the maximum number of pending accepted connections. The default is 30.
217
218     \sa setMaxPendingConnections(), hasPendingConnections()
219  */
220 int QWebSocketServer::maxPendingConnections() const
221 {
222     Q_D(const QWebSocketServer);
223     return d->maxPendingConnections();
224 }
225
226 /*!
227     Returns the next pending connection as a connected WebSocket object.
228     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.
229     0 is returned if this function is called when there are no pending connections.
230
231     Note: The returned WebSocket object cannot be used from another thread..
232
233     \sa hasPendingConnections()
234 */
235 QWebSocket *QWebSocketServer::nextPendingConnection()
236 {
237     Q_D(QWebSocketServer);
238     return d->nextPendingConnection();
239 }
240
241 /*!
242     Pauses incoming new connections. Queued connections will remain in queue.
243     \sa resumeAccepting()
244  */
245 void QWebSocketServer::pauseAccepting()
246 {
247     Q_D(QWebSocketServer);
248     d->pauseAccepting();
249 }
250
251 #ifndef QT_NO_NETWORKPROXY
252 /*!
253     Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
254
255     \sa setProxy()
256 */
257 QNetworkProxy QWebSocketServer::proxy() const
258 {
259     Q_D(const QWebSocketServer);
260     return d->proxy();
261 }
262
263 /*!
264     \brief Sets the explicit network proxy for this socket to \a networkProxy.
265
266     To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
267
268     \code
269         server->setProxy(QNetworkProxy::NoProxy);
270     \endcode
271
272     \sa proxy()
273 */
274 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
275 {
276     Q_D(QWebSocketServer);
277     d->setProxy(networkProxy);
278 }
279 #endif
280 /*!
281     Resumes accepting new connections.
282     \sa pauseAccepting()
283  */
284 void QWebSocketServer::resumeAccepting()
285 {
286     Q_D(QWebSocketServer);
287     d->resumeAccepting();
288 }
289
290 /*!
291     Sets the server name that will be used during the http handshake phase to the given \a serverName.
292     Existing connected clients will not be notified of this change, only newly connecting clients
293     will see this new name.
294  */
295 void QWebSocketServer::setServerName(const QString &serverName)
296 {
297     Q_D(QWebSocketServer);
298     d->setServerName(serverName);
299 }
300
301 /*!
302     Returns the server name that is used during the http handshake phase.
303  */
304 QString QWebSocketServer::serverName() const
305 {
306     Q_D(const QWebSocketServer);
307     return d->serverName();
308 }
309
310 /*!
311     Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
312
313     \sa serverPort(), listen()
314  */
315 QHostAddress QWebSocketServer::serverAddress() const
316 {
317     Q_D(const QWebSocketServer);
318     return d->serverAddress();
319 }
320
321 /*!
322     Returns an error code for the last error that occurred.
323     \sa errorString()
324  */
325 QAbstractSocket::SocketError QWebSocketServer::serverError() const
326 {
327     Q_D(const QWebSocketServer);
328     return d->serverError();
329 }
330
331 /*!
332     Returns the server's port if the server is listening for connections; otherwise returns 0.
333     \sa serverAddress(), listen()
334  */
335 quint16 QWebSocketServer::serverPort() const
336 {
337     Q_D(const QWebSocketServer);
338     return d->serverPort();
339 }
340
341 /*!
342     Sets the maximum number of pending accepted connections to \a numConnections.
343     WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
344     By default, the limit is 30 pending connections.
345
346     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.
347     \sa maxPendingConnections(), hasPendingConnections()
348  */
349 void QWebSocketServer::setMaxPendingConnections(int numConnections)
350 {
351     Q_D(QWebSocketServer);
352     d->setMaxPendingConnections(numConnections);
353 }
354
355 /*!
356     Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
357
358     Returns true if the socket is set successfully; otherwise returns false.
359     The socket is assumed to be in listening state.
360
361     \sa socketDescriptor(), isListening()
362  */
363 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
364 {
365     Q_D(QWebSocketServer);
366     return d->setSocketDescriptor(socketDescriptor);
367 }
368
369 /*!
370     Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
371     If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
372
373     \sa setSocketDescriptor(), isListening()
374  */
375 int QWebSocketServer::socketDescriptor() const
376 {
377     Q_D(const QWebSocketServer);
378     return d->socketDescriptor();
379 }
380
381 /*!
382     Waits for at most \a msec milliseconds or until an incoming connection is available.
383     Returns true if a connection is available; otherwise returns false.
384     If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
385
386     \note This is a blocking function call.
387     \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.
388     \note The non-blocking alternative is to connect to the newConnection() signal.
389
390     If \a msec is -1, this function will not time out.
391
392     \sa hasPendingConnections(), nextPendingConnection()
393 */
394 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
395 {
396     Q_D(QWebSocketServer);
397     return d->waitForNewConnection(msec, timedOut);
398 }
399
400 /*!
401   Returns a list of websocket versions that this server is supporting.
402  */
403 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
404 {
405     Q_D(const QWebSocketServer);
406     return d->supportedVersions();
407 }
408
409 /*!
410   Returns a list of websocket subprotocols that this server supports.
411  */
412 QList<QString> QWebSocketServer::supportedProtocols() const
413 {
414     Q_D(const QWebSocketServer);
415     return d->supportedProtocols();
416 }
417
418 /*!
419   Returns a list of websocket extensions that this server supports.
420  */
421 QList<QString> QWebSocketServer::supportedExtensions() const
422 {
423     Q_D(const QWebSocketServer);
424     return d->supportedExtensions();
425 }
426
427 QT_END_NAMESPACE