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