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