1 /****************************************************************************
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
45 \inmodule QtWebSockets
46 \brief Implements a TCP socket that talks the websocket protocol.
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.
54 This class was modeled after QAbstractSocket.
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}.
60 QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
61 \l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
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.
72 \sa QAbstractSocket, QTcpSocket
74 \sa {QWebSocket client example}
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
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.
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.
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.
97 \snippet echoclient/echoclient.cpp onTextMessageReceived
98 Whenever a message is received, we write it out.
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()
109 \fn void QWebSocket::disconnected()
110 \brief Emitted when the socket is disconnected.
111 \sa close(), connected()
114 \fn void QWebSocket::aboutToClose()
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).
123 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
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.
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.
134 \sa QAuthenticator, QNetworkProxy
137 \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
139 This signal is emitted whenever QWebSocket's state changes.
140 The \a state parameter is the new state.
142 \note QAbstractSocket::ConnectedState is emitted after the handshake has
143 with the server has succeeded.
145 QAbstractSocket::SocketState is not a registered metatype, so for queued
146 connections, you will have to register it with Q_REGISTER_METATYPE() and
152 \fn void QWebSocket::readChannelFinished()
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.
160 \fn void QWebSocket::bytesWritten(qint64 bytes)
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.
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()).
172 \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
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.
177 This signal can be used to process large messages frame by frame, instead of waiting for the
178 complete message to arrive.
180 \sa binaryFrameReceived()
183 \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
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.
188 This signal can be used to process large messages frame by frame, instead of waiting for the
189 complete message to arrive.
191 \sa textFrameReceived()
194 \fn void QWebSocket::textMessageReceived(const QString &message);
196 This signal is emitted whenever a text message is received. The \a message contains the
199 \sa binaryMessageReceived()
202 \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
204 This signal is emitted whenever a binary message is received. The \a message contains the
207 \sa textMessageReceived()
210 \fn void QWebSocket::error(QAbstractSocket::SocketError error);
212 This signal is emitted after an error occurred. The \a error
213 parameter describes the type of error that occurred.
215 QAbstractSocket::SocketError is not a registered metatype, so for queued
216 connections, you will have to register it with Q_DECLARE_METATYPE() and
219 \sa error(), errorString()
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()
232 \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
235 \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
236 QWebSocket::ignoreSslErrors() will have no effect.
239 \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
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.
247 #include "qwebsocket.h"
248 #include "qwebsocket_p.h"
250 #include <QtCore/QUrl>
251 #include <QtNetwork/QTcpSocket>
252 #include <QtCore/QByteArray>
253 #include <QtNetwork/QHostAddress>
255 #include <QtCore/QDebug>
262 * \brief Creates a new QWebSocket with the given \a origin,
263 * the \a version of the protocol to use and \a parent.
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
272 QWebSocket::QWebSocket(const QString &origin,
273 QWebSocketProtocol::Version version,
275 QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
282 * \brief Destroys the QWebSocket. Closes the socket if it is still open,
283 * and releases any used resources.
285 QWebSocket::~QWebSocket()
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.
294 void QWebSocket::abort()
301 * Returns the type of error that last occurred
304 QAbstractSocket::SocketError QWebSocket::error() const
306 Q_D(const QWebSocket);
310 //only called by QWebSocketPrivate::upgradeFrom
314 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
315 QWebSocketProtocol::Version version, QObject *parent) :
316 QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
323 * Returns a human-readable description of the last error that occurred
327 QString QWebSocket::errorString() const
329 Q_D(const QWebSocket);
330 return d->errorString();
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.
343 bool QWebSocket::flush()
350 \brief Sends the given \a message over the socket as a text message and
351 returns the number of bytes actually sent.
353 \sa sendBinaryMessage()
355 qint64 QWebSocket::sendTextMessage(const QString &message)
358 return d->sendTextMessage(message);
362 \brief Sends the given \a data over the socket as a binary message and
363 returns the number of bytes actually sent.
365 \sa sendTextMessage()
367 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
370 return d->sendBinaryMessage(data);
374 \brief Gracefully closes the socket with the given \a closeCode and \a reason.
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
380 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
383 d->close(closeCode, reason);
387 \brief Opens a websocket connection using the given \a url.
389 If the url contains newline characters (\\r\\n), then the error signal will be emitted
390 with QAbstractSocket::ConnectionRefusedError as error type.
392 void QWebSocket::open(const QUrl &url)
399 \brief Pings the server to indicate that the connection is still alive.
400 Additional \a payload can be sent along the ping message.
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.
407 void QWebSocket::ping(const QByteArray &payload)
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
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
432 \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
434 void QWebSocket::ignoreSslErrors()
437 d->ignoreSslErrors();
443 This method tells QWebSocket to ignore the errors given in \a errors.
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:
449 \snippet src_websockets_ssl_qwebsocket.cpp 6
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.
458 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
461 d->ignoreSslErrors(errors);
465 Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
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()
472 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
475 d->setSslConfiguration(sslConfiguration);
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.
484 \sa setSslConfiguration()
486 QSslConfiguration QWebSocket::sslConfiguration() const
488 Q_D(const QWebSocket);
489 return d->sslConfiguration();
492 #endif //not QT_NO_SSL
495 \brief Returns the version the socket is currently using
497 QWebSocketProtocol::Version QWebSocket::version() const
499 Q_D(const QWebSocket);
504 \brief Returns the name of the resource currently accessed.
506 QString QWebSocket::resourceName() const
508 Q_D(const QWebSocket);
509 return d->resourceName();
513 \brief Returns the url the socket is connected to or will connect to.
515 QUrl QWebSocket::requestUrl() const
517 Q_D(const QWebSocket);
518 return d->requestUrl();
522 \brief Returns the current origin
524 QString QWebSocket::origin() const
526 Q_D(const QWebSocket);
531 \brief Returns the code indicating why the socket was closed.
532 \sa QWebSocketProtocol::CloseCode, closeReason()
534 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
536 Q_D(const QWebSocket);
537 return d->closeCode();
541 \brief Returns the reason why the socket was closed.
544 QString QWebSocket::closeReason() const
546 Q_D(const QWebSocket);
547 return d->closeReason();
551 \brief Returns the current state of the socket
553 QAbstractSocket::SocketState QWebSocket::state() const
555 Q_D(const QWebSocket);
560 Returns the local address
562 QHostAddress QWebSocket::localAddress() const
564 Q_D(const QWebSocket);
565 return d->localAddress();
569 Returns the local port
571 quint16 QWebSocket::localPort() const
573 Q_D(const QWebSocket);
574 return d->localPort();
578 Returns the pause mode of this socket
580 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
582 Q_D(const QWebSocket);
583 return d->pauseMode();
587 Returns the peer address
589 QHostAddress QWebSocket::peerAddress() const
591 Q_D(const QWebSocket);
592 return d->peerAddress();
598 QString QWebSocket::peerName() const
600 Q_D(const QWebSocket);
601 return d->peerName();
607 quint16 QWebSocket::peerPort() const
609 Q_D(const QWebSocket);
610 return d->peerPort();
613 #ifndef QT_NO_NETWORKPROXY
615 Returns the currently configured proxy
617 QNetworkProxy QWebSocket::proxy() const
619 Q_D(const QWebSocket);
624 Sets the proxy to \a networkProxy
626 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
629 d->setProxy(networkProxy);
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.
638 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
641 d->setMaskGenerator(maskGenerator);
645 Returns the mask generator that is currently used by this QWebSocket.
647 const QMaskGenerator *QWebSocket::maskGenerator() const
649 Q_D(const QWebSocket);
650 return d->maskGenerator();
654 Returns the size in bytes of the readbuffer that is used by the socket.
656 qint64 QWebSocket::readBufferSize() const
658 Q_D(const QWebSocket);
659 return d->readBufferSize();
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.
668 \sa pauseMode(), setPauseMode()
670 void QWebSocket::resume()
677 Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
678 the conditions in which the socket should be paused.
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.
686 \sa pauseMode(), resume()
688 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
691 d->setPauseMode(pauseMode);
695 Sets the size of QWebSocket's internal read buffer to be \a size bytes.
697 If the buffer size is limited to a certain size, QWebSocket won't buffer more than
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.
707 void QWebSocket::setReadBufferSize(qint64 size)
710 d->setReadBufferSize(size);
714 Returns \c true if the socket is ready for reading and writing; otherwise
717 bool QWebSocket::isValid() const
719 Q_D(const QWebSocket);