Made parameters const references
[contrib/qtwebsockets.git] / src / qwebsocketserver.cpp
1 /*
2 QWebSockets implements the WebSocket protocol as defined in RFC 6455.
3 Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18 */
19
20 /*!
21     \class QWebSocketServer
22
23     \inmodule QWebSockets
24
25     \brief Implements a websocket-based server.
26
27     It is modeled after QTcpServer, and behaves the same. So, if you know how to use QTcpServer, you know how to use QWebSocketServer.
28     This class makes it possible to accept incoming websocket connections.
29     You can specify the port or have QWebSocketServer pick one automatically.
30     You can listen on a specific address or on all the machine's addresses.
31     Call listen() to have the server listen for incoming connections.
32
33     The newConnection() signal is then emitted each time a client connects to the server.
34     Call nextPendingConnection() to accept the pending connection as a connected QWebSocket.
35     The function returns a pointer to a QWebSocket in QAbstractSocket::ConnectedState that you can use for communicating with the client.
36     If an error occurs, serverError() returns the type of error, and errorString() can be called to get a human readable description of what happened.
37     When listening for connections, the address and port on which the server is listening are available as serverAddress() and serverPort().
38     Calling close() makes QWebSocketServer stop listening for incoming connections.
39     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.
40
41     \sa echoserver.html
42
43     \sa QWebSocket
44 */
45
46 /*!
47   \page echoserver.html example
48   \title WebSocket server example
49   \brief A sample websocket server echoing back messages sent to it.
50
51   \section1 Description
52   The echoserver example implements a web socket server that echoes back everything that is sent to it.
53   \section1 Code
54   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.
55   \snippet echoserver.cpp constructor
56   If listening is successful, we connect the `newConnection()` signal to the slot `onNewConnection()`.
57   The `newConnection()` signal will be thrown whenever a new web socket client is connected to our server.
58
59   \snippet echoserver.cpp onNewConnection
60   When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`), and the signals we are interested in
61   are connected to our slots (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
62   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).
63
64   \snippet echoserver.cpp processMessage
65   Whenever `processMessage()` is triggered, we retrieve the sender, and if valid, send back the original message (`send()`).
66   The same is done with binary messages.
67   \snippet echoserver.cpp processBinaryMessage
68   The only difference is that the message now is a QByteArray instead of a QString.
69
70   \snippet echoserver.cpp socketDisconnected
71   Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
72   Note: it is best to use `deleteLater()` to delete the socket.
73 */
74
75 /*!
76     \fn void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
77     This signal is emitted when accepting a new connection results in an error.
78     The \a socketError parameter describes the type of error that occurred
79
80     \sa pauseAccepting(), resumeAccepting()
81 */
82
83 /*!
84     \fn void QWebSocketServer::newConnection()
85     This signal is emitted every time a new connection is available.
86
87     \sa hasPendingConnections(), nextPendingConnection()
88 */
89
90 #include <QTcpServer>
91 #include <QTcpSocket>
92 #include <QNetworkProxy>
93 #include "qwebsocketprotocol.h"
94 #include "qwebsocket.h"
95 #include "qwebsocketserver.h"
96 #include "qwebsocketserver_p.h"
97
98 QT_BEGIN_NAMESPACE
99
100 /*!
101     Constructs a new WebSocketServer with the given \a serverName.
102     The \a serverName will be used in the http handshake phase to identify the server.
103
104     \a parent is passed to the QObject constructor.
105  */
106 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
107     QObject(parent),
108     d_ptr(new QWebSocketServerPrivate(serverName, this, this))
109 {
110 }
111
112 /*!
113     Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
114     Any client WebSockets that are still connected are closed and deleted.
115
116     \sa close()
117  */
118 QWebSocketServer::~QWebSocketServer()
119 {
120     delete d_ptr;
121 }
122
123 /*!
124   Closes the server. The server will no longer listen for incoming connections.
125  */
126 void QWebSocketServer::close()
127 {
128     d_ptr->close();
129 }
130
131 /*!
132     Returns a human readable description of the last error that occurred.
133
134     \sa serverError()
135 */
136 QString QWebSocketServer::errorString() const
137 {
138     return d_ptr->errorString();
139 }
140
141 /*!
142     Returns true if the server has pending connections; otherwise returns false.
143
144     \sa nextPendingConnection(), setMaxPendingConnections()
145  */
146 bool QWebSocketServer::hasPendingConnections() const
147 {
148     return d_ptr->hasPendingConnections();
149 }
150
151 /*!
152     Returns true if the server is currently listening for incoming connections; otherwise returns false.
153
154     \sa listen()
155  */
156 bool QWebSocketServer::isListening() const
157 {
158     return d_ptr->isListening();
159 }
160
161 /*!
162     Tells the server to listen for incoming connections on address \a address and port \a port.
163     If \a port is 0, a port is chosen automatically.
164     If \a address is QHostAddress::Any, the server will listen on all network interfaces.
165
166     Returns true on success; otherwise returns false.
167
168     \sa isListening()
169  */
170 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
171 {
172     return d_ptr->listen(address, port);
173 }
174
175 /*!
176     Returns the maximum number of pending accepted connections. The default is 30.
177
178     \sa setMaxPendingConnections(), hasPendingConnections()
179  */
180 int QWebSocketServer::maxPendingConnections() const
181 {
182     return d_ptr->maxPendingConnections();
183 }
184
185 /*!
186     Returns the next pending connection as a connected WebSocket object.
187     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.
188     0 is returned if this function is called when there are no pending connections.
189
190     Note: The returned WebSocket object cannot be used from another thread..
191
192     \sa hasPendingConnections()
193 */
194 QWebSocket *QWebSocketServer::nextPendingConnection()
195 {
196     return d_ptr->nextPendingConnection();
197 }
198
199 /*!
200     Pauses incoming new connections. Queued connections will remain in queue.
201     \sa resumeAccepting()
202  */
203 void QWebSocketServer::pauseAccepting()
204 {
205     d_ptr->pauseAccepting();
206 }
207
208 #ifndef QT_NO_NETWORKPROXY
209 /*!
210     Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
211
212     \sa setProxy()
213 */
214 QNetworkProxy QWebSocketServer::proxy() const
215 {
216     return d_ptr->proxy();
217 }
218
219 /*!
220     \brief Sets the explicit network proxy for this socket to \a networkProxy.
221
222     To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
223
224     \code
225         server->setProxy(QNetworkProxy::NoProxy);
226     \endcode
227
228     \sa proxy()
229 */
230 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
231 {
232     d_ptr->setProxy(networkProxy);
233 }
234 #endif
235 /*!
236     Resumes accepting new connections.
237     \sa pauseAccepting()
238  */
239 void QWebSocketServer::resumeAccepting()
240 {
241     d_ptr->resumeAccepting();
242 }
243
244 /*!
245     Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
246
247     \sa serverPort(), listen()
248  */
249 QHostAddress QWebSocketServer::serverAddress() const
250 {
251     return d_ptr->serverAddress();
252 }
253
254 /*!
255     Returns an error code for the last error that occurred.
256     \sa errorString()
257  */
258 QAbstractSocket::SocketError QWebSocketServer::serverError() const
259 {
260     return d_ptr->serverError();
261 }
262
263 /*!
264     Returns the server's port if the server is listening for connections; otherwise returns 0.
265     \sa serverAddress(), listen()
266  */
267 quint16 QWebSocketServer::serverPort() const
268 {
269     return d_ptr->serverPort();
270 }
271
272 /*!
273     Sets the maximum number of pending accepted connections to \a numConnections.
274     WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
275     By default, the limit is 30 pending connections.
276
277     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.
278     \sa maxPendingConnections(), hasPendingConnections()
279  */
280 void QWebSocketServer::setMaxPendingConnections(int numConnections)
281 {
282     d_ptr->setMaxPendingConnections(numConnections);
283 }
284
285 /*!
286     Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
287
288     Returns true if the socket is set successfully; otherwise returns false.
289     The socket is assumed to be in listening state.
290
291     \sa socketDescriptor(), isListening()
292  */
293 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
294 {
295     return d_ptr->setSocketDescriptor(socketDescriptor);
296 }
297
298 /*!
299     Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
300     If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
301
302     \sa setSocketDescriptor(), isListening()
303  */
304 int QWebSocketServer::socketDescriptor() const
305 {
306     return d_ptr->socketDescriptor();
307 }
308
309 /*!
310     Waits for at most \a msec milliseconds or until an incoming connection is available.
311     Returns true if a connection is available; otherwise returns false.
312     If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
313
314     \note This is a blocking function call.
315     \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.
316     \note The non-blocking alternative is to connect to the newConnection() signal.
317
318     If \a msec is -1, this function will not time out.
319
320     \sa hasPendingConnections(), nextPendingConnection()
321 */
322 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
323 {
324     return d_ptr->waitForNewConnection(msec, timedOut);
325 }
326
327 /*!
328   Returns a list of websocket versions that this server is supporting.
329  */
330 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
331 {
332     return d_ptr->supportedVersions();
333 }
334
335 /*!
336   Returns a list of websocket subprotocols that this server supports.
337  */
338 QList<QString> QWebSocketServer::supportedProtocols() const
339 {
340     return d_ptr->supportedProtocols();
341 }
342
343 /*!
344   Returns a list of websocket extensions that this server supports.
345  */
346 QList<QString> QWebSocketServer::supportedExtensions() const
347 {
348     return d_ptr->supportedExtensions();
349 }
350
351 /*!
352     This method checks if the given \a origin is allowed; it returns true when the \a origin is allowed, otherwise false.
353     It is supposed to be overriden by a subclass to filter out unwanted origins.
354     By default, every origin is accepted.
355
356     \note Checking on the origin does not make much sense when the server is accessed
357 via a non-browser client, as that client can set whatever origin header it likes
358 In case of a browser client, the server SHOULD check the validity of the origin.
359 \sa http://tools.ietf.org/html/rfc6455#section-10
360 */
361 bool QWebSocketServer::isOriginAllowed(const QString &origin) const
362 {
363     Q_UNUSED(origin)
364     return true;
365 }
366
367 QT_END_NAMESPACE