Cleanup header file
[contrib/qtwebsockets.git] / src / websockets / qwebsocket.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 QWebSocket
44
45     \inmodule QtWebSockets
46     \brief Implements a TCP socket that talks the websocket protocol.
47
48     WebSockets is a web technology providing full-duplex communications channels over
49     a single TCP connection.
50     The WebSocket protocol was standardized by the IETF as
51     \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
52     QWebSocket can both be used in a client application and server application.
53
54     This class was modeled after QAbstractSocket.
55
56     QWebSocket currently does not support
57     \l {http://tools.ietf.org/html/rfc6455#page-39} {extensions} and
58     \l {http://tools.ietf.org/html/rfc6455#page-12} {subprotocols}.
59
60     QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
61     \l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
62
63     \warning To generate masks, this implementation of WebSockets uses the cryptographically
64     insecure qrand() function.
65     For more information about the importance of good masking,
66     see \l {http://w2spconf.com/2011/papers/websocket.pdf}.
67     The best measure against attacks mentioned in the document above,
68     is to use QWebSocket over a secure connection (\e wss://).
69     In general, always be careful to not have 3rd party script access to
70     a QWebSocket in your application.
71
72     \sa QAbstractSocket, QTcpSocket
73
74     \sa {QWebSocket client example}
75 */
76
77 /*!
78     \page echoclient.html example
79     \title QWebSocket client example
80     \brief A sample websocket client that sends a message and displays the message that
81     it receives back.
82
83     \section1 Description
84     The EchoClient example implements a web socket client that sends a message to a websocket server
85     and dumps the answer that it gets back.
86     This example should ideally be used with the EchoServer example.
87     \section1 Code
88     We start by connecting to the `connected()` signal.
89     \snippet echoclient/echoclient.cpp constructor
90     After the connection, we open the socket to the given \a url.
91
92     \snippet echoclient/echoclient.cpp onConnected
93     When the client is connected successfully, we connect to the `onTextMessageReceived()` signal,
94     and send out "Hello, world!".
95     If connected with the EchoServer, we will receive the same message back.
96
97     \snippet echoclient/echoclient.cpp onTextMessageReceived
98     Whenever a message is received, we write it out.
99 */
100
101 /*!
102   \fn void QWebSocket::connected()
103   \brief Emitted when a connection is successfully established.
104   A connection is successfully established when the socket is connected
105   and the handshake was successful.
106   \sa open(), disconnected()
107 */
108 /*!
109   \fn void QWebSocket::disconnected()
110   \brief Emitted when the socket is disconnected.
111   \sa close(), connected()
112 */
113 /*!
114     \fn void QWebSocket::aboutToClose()
115
116     This signal is emitted when the socket is about to close.
117     Connect this signal if you have operations that need to be performed before the socket closes
118     (e.g., if you have data in a separate buffer that needs to be written to the device).
119
120     \sa close()
121  */
122 /*!
123 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
124
125 This signal can be emitted when a \a proxy that requires
126 authentication is used. The \a authenticator object can then be
127 filled in with the required details to allow authentication and
128 continue the connection.
129
130 \note It is not possible to use a QueuedConnection to connect to
131 this signal, as the connection will fail if the authenticator has
132 not been filled in with new information when the signal returns.
133
134 \sa QAuthenticator, QNetworkProxy
135 */
136 /*!
137     \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
138
139     This signal is emitted whenever QWebSocket's state changes.
140     The \a state parameter is the new state.
141
142     \note QAbstractSocket::ConnectedState is emitted after the handshake has
143     with the server has succeeded.
144
145     QAbstractSocket::SocketState is not a registered metatype, so for queued
146     connections, you will have to register it with Q_REGISTER_METATYPE() and
147     qRegisterMetaType().
148
149     \sa state()
150 */
151 /*!
152     \fn void QWebSocket::readChannelFinished()
153
154     This signal is emitted when the input (reading) stream is closed in this device.
155     It is emitted as soon as the closing is detected.
156
157     \sa close()
158 */
159 /*!
160     \fn void QWebSocket::bytesWritten(qint64 bytes)
161
162     This signal is emitted every time a payload of data has been written to the socket.
163     The \a bytes argument is set to the number of bytes that were written in this payload.
164
165     \note This signal has the same meaning both for secure and non-secure websockets.
166     As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively
167     written (see QSslSocket:encryptedBytesWritten()).
168     \sa close()
169 */
170
171 /*!
172     \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
173
174     This signal is emitted whenever a text frame is received. The \a frame contains the data and
175     \a isLastFrame indicates whether this is the last frame of the complete message.
176
177     This signal can be used to process large messages frame by frame, instead of waiting for the
178     complete message to arrive.
179
180     \sa binaryFrameReceived()
181 */
182 /*!
183     \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
184
185     This signal is emitted whenever a binary frame is received. The \a frame contains the data and
186     \a isLastFrame indicates whether this is the last frame of the complete message.
187
188     This signal can be used to process large messages frame by frame, instead of waiting for the
189     complete message to arrive.
190
191     \sa textFrameReceived()
192 */
193 /*!
194     \fn void QWebSocket::textMessageReceived(const QString &message);
195
196     This signal is emitted whenever a text message is received. The \a message contains the
197     received text.
198
199     \sa binaryMessageReceived()
200 */
201 /*!
202     \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
203
204     This signal is emitted whenever a binary message is received. The \a message contains the
205     received bytes.
206
207     \sa textMessageReceived()
208 */
209 /*!
210     \fn void QWebSocket::error(QAbstractSocket::SocketError error);
211
212     This signal is emitted after an error occurred. The \a error
213     parameter describes the type of error that occurred.
214
215     QAbstractSocket::SocketError is not a registered metatype, so for queued
216     connections, you will have to register it with Q_DECLARE_METATYPE() and
217     qRegisterMetaType().
218
219     \sa error(), errorString()
220 */
221 /*!
222     \fn void QWebSocket::sslErrors(const QList<QSslError> &errors)
223     QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have
224     occurred while establishing the identity of the peer.
225     The errors are usually an indication that QWebSocket is unable to securely identify the peer.
226     Unless any action is taken, the connection will be dropped after this signal has been emitted.
227     If you want to continue connecting despite the errors that have occurred, you must call
228     QWebSocket::ignoreSslErrors() from inside a slot connected to this signal.
229     If you need to access the error list at a later point, you can call sslErrors()
230     (without arguments).
231
232     \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
233     the peer.
234
235     \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
236     QWebSocket::ignoreSslErrors() will have no effect.
237 */
238 /*!
239     \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
240
241     Emitted when a pong message is received in reply to a previous ping.
242     \a elapsedTime contains the roundtrip time in milliseconds and \a payload contains an optional
243     payload that was sent with the ping.
244
245     \sa ping()
246   */
247 #include "qwebsocket.h"
248 #include "qwebsocket_p.h"
249
250 #include <QtCore/QUrl>
251 #include <QtNetwork/QTcpSocket>
252 #include <QtCore/QByteArray>
253 #include <QtNetwork/QHostAddress>
254
255 #include <QtCore/QDebug>
256
257 #include <limits>
258
259 QT_BEGIN_NAMESPACE
260
261 /*!
262  * \brief Creates a new QWebSocket with the given \a origin,
263  * the \a version of the protocol to use and \a parent.
264  *
265  * The \a origin of the client is as specified \l {http://tools.ietf.org/html/rfc6454}{RFC 6454}.
266  * (The \a origin is not required for non-web browser clients
267  * (see \l {http://tools.ietf.org/html/rfc6455}{RFC 6455})).
268  * The \a origin may not contain new line characters, otherwise the connection will be
269  * aborted immediately during the handshake phase.
270  * \note Currently only V13 (\l {http://tools.ietf.org/html/rfc6455} {RFC 6455}) is supported
271  */
272 QWebSocket::QWebSocket(const QString &origin,
273                        QWebSocketProtocol::Version version,
274                        QObject *parent) :
275     QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
276 {
277     Q_D(QWebSocket);
278     d->init();
279 }
280
281 /*!
282  * \brief Destroys the QWebSocket. Closes the socket if it is still open,
283  * and releases any used resources.
284  */
285 QWebSocket::~QWebSocket()
286 {
287 }
288
289 /*!
290  * \brief Aborts the current socket and resets the socket.
291  * Unlike close(), this function immediately closes the socket,
292  * discarding any pending data in the write buffer.
293  */
294 void QWebSocket::abort()
295 {
296     Q_D(QWebSocket);
297     d->abort();
298 }
299
300 /*!
301  * Returns the type of error that last occurred
302  * \sa errorString()
303  */
304 QAbstractSocket::SocketError QWebSocket::error() const
305 {
306     Q_D(const QWebSocket);
307     return d->error();
308 }
309
310 //only called by QWebSocketPrivate::upgradeFrom
311 /*!
312   \internal
313  */
314 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
315                        QWebSocketProtocol::Version version, QObject *parent) :
316     QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
317 {
318     Q_D(QWebSocket);
319     d->init();
320 }
321
322 /*!
323  * Returns a human-readable description of the last error that occurred
324  *
325  * \sa error()
326  */
327 QString QWebSocket::errorString() const
328 {
329     Q_D(const QWebSocket);
330     return d->errorString();
331 }
332
333 /*!
334     This function writes as much as possible from the internal write buffer
335     to the underlying network socket, without blocking.
336     If any data was written, this function returns true; otherwise false is returned.
337     Call this function if you need QWebSocket to start sending buffered data immediately.
338     The number of bytes successfully written depends on the operating system.
339     In most cases, you do not need to call this function,
340     because QWebSocket will start sending data automatically
341     once control goes back to the event loop.
342 */
343 bool QWebSocket::flush()
344 {
345     Q_D(QWebSocket);
346     return d->flush();
347 }
348
349 /*!
350     \brief Sends the given \a message over the socket as a text message and
351     returns the number of bytes actually sent.
352
353     \sa sendBinaryMessage()
354  */
355 qint64 QWebSocket::sendTextMessage(const QString &message)
356 {
357     Q_D(QWebSocket);
358     return d->sendTextMessage(message);
359 }
360
361 /*!
362     \brief Sends the given \a data over the socket as a binary message and
363     returns the number of bytes actually sent.
364
365     \sa sendTextMessage()
366  */
367 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
368 {
369     Q_D(QWebSocket);
370     return d->sendBinaryMessage(data);
371 }
372
373 /*!
374     \brief Gracefully closes the socket with the given \a closeCode and \a reason.
375
376     Any data in the write buffer is flushed before the socket is closed.
377     The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
378     \a reason describes the reason of the closure more in detail
379  */
380 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
381 {
382     Q_D(QWebSocket);
383     d->close(closeCode, reason);
384 }
385
386 /*!
387     \brief Opens a websocket connection using the given \a url.
388
389     If the url contains newline characters (\\r\\n), then the error signal will be emitted
390     with QAbstractSocket::ConnectionRefusedError as error type.
391  */
392 void QWebSocket::open(const QUrl &url)
393 {
394     Q_D(QWebSocket);
395     d->open(url, true);
396 }
397
398 /*!
399     \brief Pings the server to indicate that the connection is still alive.
400     Additional \a payload can be sent along the ping message.
401
402     The size of the \a payload cannot be bigger than 125.
403     If it is larger, the \a payload is clipped to 125 bytes.
404
405     \sa pong()
406  */
407 void QWebSocket::ping(const QByteArray &payload)
408 {
409     Q_D(QWebSocket);
410     d->ping(payload);
411 }
412
413 #ifndef QT_NO_SSL
414 /*!
415     This slot tells QWebSocket to ignore errors during QWebSocket's
416     handshake phase and continue connecting. If you want to continue
417     with the connection even if errors occur during the handshake
418     phase, then you must call this slot, either from a slot connected
419     to sslErrors(), or before the handshake phase. If you don't call
420     this slot, either in response to errors or before the handshake,
421     the connection will be dropped after the sslErrors() signal has
422     been emitted.
423
424     \warning Be sure to always let the user inspect the errors
425     reported by the sslErrors() signal, and only call this method
426     upon confirmation from the user that proceeding is ok.
427     If there are unexpected errors, the connection should be aborted.
428     Calling this method without inspecting the actual errors will
429     most likely pose a security risk for your application. Use it
430     with great care!
431
432     \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
433 */
434 void QWebSocket::ignoreSslErrors()
435 {
436     Q_D(QWebSocket);
437     d->ignoreSslErrors();
438 }
439
440 /*!
441     \overload
442
443     This method tells QWebSocket to ignore the errors given in \a errors.
444
445     Note that you can set the expected certificate in the SSL error:
446     If, for instance, you want to connect to a server that uses
447     a self-signed certificate, consider the following snippet:
448
449     \snippet src_websockets_ssl_qwebsocket.cpp 6
450
451     Multiple calls to this function will replace the list of errors that
452     were passed in previous calls.
453     You can clear the list of errors you want to ignore by calling this
454     function with an empty list.
455
456     \sa sslErrors()
457 */
458 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
459 {
460     Q_D(QWebSocket);
461     d->ignoreSslErrors(errors);
462 }
463
464 /*!
465     Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
466
467     This function sets the local certificate, the ciphers, the private key and
468     the CA certificates to those stored in \a sslConfiguration.
469     It is not possible to set the SSL-state related fields.
470     \sa sslConfiguration()
471  */
472 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
473 {
474     Q_D(QWebSocket);
475     d->setSslConfiguration(sslConfiguration);
476 }
477
478 /*!
479     Returns the socket's SSL configuration state.
480     The default SSL configuration of a socket is to use the default ciphers,
481     default CA certificates, no local private key or certificate.
482     The SSL configuration also contains fields that can change with time without notice.
483
484     \sa setSslConfiguration()
485  */
486 QSslConfiguration QWebSocket::sslConfiguration() const
487 {
488     Q_D(const QWebSocket);
489     return d->sslConfiguration();
490 }
491
492 #endif  //not QT_NO_SSL
493
494 /*!
495     \brief Returns the version the socket is currently using
496  */
497 QWebSocketProtocol::Version QWebSocket::version() const
498 {
499     Q_D(const QWebSocket);
500     return d->version();
501 }
502
503 /*!
504     \brief Returns the name of the resource currently accessed.
505  */
506 QString QWebSocket::resourceName() const
507 {
508     Q_D(const QWebSocket);
509     return d->resourceName();
510 }
511
512 /*!
513     \brief Returns the url the socket is connected to or will connect to.
514  */
515 QUrl QWebSocket::requestUrl() const
516 {
517     Q_D(const QWebSocket);
518     return d->requestUrl();
519 }
520
521 /*!
522     \brief Returns the current origin
523  */
524 QString QWebSocket::origin() const
525 {
526     Q_D(const QWebSocket);
527     return d->origin();
528 }
529
530 /*!
531     \brief Returns the code indicating why the socket was closed.
532     \sa QWebSocketProtocol::CloseCode, closeReason()
533  */
534 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
535 {
536     Q_D(const QWebSocket);
537     return d->closeCode();
538 }
539
540 /*!
541     \brief Returns the reason why the socket was closed.
542     \sa closeCode()
543  */
544 QString QWebSocket::closeReason() const
545 {
546     Q_D(const QWebSocket);
547     return d->closeReason();
548 }
549
550 /*!
551     \brief Returns the current state of the socket
552  */
553 QAbstractSocket::SocketState QWebSocket::state() const
554 {
555     Q_D(const QWebSocket);
556     return d->state();
557 }
558
559 /*!
560     Returns the local address
561  */
562 QHostAddress QWebSocket::localAddress() const
563 {
564     Q_D(const QWebSocket);
565     return d->localAddress();
566 }
567
568 /*!
569     Returns the local port
570  */
571 quint16 QWebSocket::localPort() const
572 {
573     Q_D(const QWebSocket);
574     return d->localPort();
575 }
576
577 /*!
578     Returns the pause mode of this socket
579  */
580 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
581 {
582     Q_D(const QWebSocket);
583     return d->pauseMode();
584 }
585
586 /*!
587     Returns the peer address
588  */
589 QHostAddress QWebSocket::peerAddress() const
590 {
591     Q_D(const QWebSocket);
592     return d->peerAddress();
593 }
594
595 /*!
596     Returns the peerName
597  */
598 QString QWebSocket::peerName() const
599 {
600     Q_D(const QWebSocket);
601     return d->peerName();
602 }
603
604 /*!
605     Returns the peerport
606  */
607 quint16 QWebSocket::peerPort() const
608 {
609     Q_D(const QWebSocket);
610     return d->peerPort();
611 }
612
613 #ifndef QT_NO_NETWORKPROXY
614 /*!
615     Returns the currently configured proxy
616  */
617 QNetworkProxy QWebSocket::proxy() const
618 {
619     Q_D(const QWebSocket);
620     return d->proxy();
621 }
622
623 /*!
624     Sets the proxy to \a networkProxy
625  */
626 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
627 {
628     Q_D(QWebSocket);
629     d->setProxy(networkProxy);
630 }
631 #endif
632
633 /*!
634     Sets the generator to use for creating masks to \a maskGenerator.
635     The default QWebSocket generator can be reset by supplying a \e Q_NULLPTR.
636     The mask generator can be changed at any time, even while the connection is open.
637  */
638 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
639 {
640     Q_D(QWebSocket);
641     d->setMaskGenerator(maskGenerator);
642 }
643
644 /*!
645     Returns the mask generator that is currently used by this QWebSocket.
646  */
647 const QMaskGenerator *QWebSocket::maskGenerator() const
648 {
649     Q_D(const QWebSocket);
650     return d->maskGenerator();
651 }
652
653 /*!
654     Returns the size in bytes of the readbuffer that is used by the socket.
655  */
656 qint64 QWebSocket::readBufferSize() const
657 {
658     Q_D(const QWebSocket);
659     return d->readBufferSize();
660 }
661
662 /*!
663     Continues data transfer on the socket. This method should only be used after the socket
664     has been set to pause upon notifications and a notification has been received.
665     The only notification currently supported is sslErrors().
666     Calling this method if the socket is not paused results in undefined behavior.
667
668     \sa pauseMode(), setPauseMode()
669  */
670 void QWebSocket::resume()
671 {
672     Q_D(QWebSocket);
673     d->resume();
674 }
675
676 /*!
677     Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
678     the conditions in which the socket should be paused.
679
680     The only notification currently supported is sslErrors().
681     If set to PauseOnSslErrors, data transfer on the socket will be paused
682     and needs to be enabled explicitly again by calling resume().
683     By default, this option is set to PauseNever. This option must be called
684     before connecting to the server, otherwise it will result in undefined behavior.
685
686     \sa pauseMode(), resume()
687  */
688 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
689 {
690     Q_D(QWebSocket);
691     d->setPauseMode(pauseMode);
692 }
693
694 /*!
695     Sets the size of QWebSocket's internal read buffer to be \a size bytes.
696
697     If the buffer size is limited to a certain size, QWebSocket won't buffer more than
698     this size of data.
699     Exceptionally, a buffer size of 0 means that the read buffer is unlimited and
700     all incoming data is buffered. This is the default.
701     This option is useful if you only read the data at certain points in time
702     (e.g., in a real-time streaming application) or if you want to protect your socket against
703     receiving too much data, which may eventually cause your application to run out of memory.
704
705     \sa readBufferSize()
706 */
707 void QWebSocket::setReadBufferSize(qint64 size)
708 {
709     Q_D(QWebSocket);
710     d->setReadBufferSize(size);
711 }
712
713 /*!
714     Returns \c true if the socket is ready for reading and writing; otherwise
715     returns \c false.
716  */
717 bool QWebSocket::isValid() const
718 {
719     Q_D(const QWebSocket);
720     return d->isValid();
721 }
722
723 QT_END_NAMESPACE