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 \note Some proxies do not understand certain HTTP headers used during a WebSocket handshake.
64 In that case, non-secure WebSocket connections fail. The best way to mitigate against
65 this problem is to use WebSocket over a secure connection.
67 \warning To generate masks, this implementation of WebSockets uses the cryptographically
68 insecure qrand() function.
69 For more information about the importance of good masking,
70 see \l {http://w2spconf.com/2011/papers/websocket.pdf}.
71 The best measure against attacks mentioned in the document above,
72 is to use QWebSocket over a secure connection (\e wss://).
73 In general, always be careful to not have 3rd party script access to
74 a QWebSocket in your application.
76 \sa QAbstractSocket, QTcpSocket
78 \sa {QWebSocket client example}
82 \page echoclient.html example
83 \title QWebSocket client example
84 \brief A sample WebSocket client that sends a message and displays the message that
88 The EchoClient example implements a WebSocket client that sends a message to a WebSocket server
89 and dumps the answer that it gets back.
90 This example should ideally be used with the EchoServer example.
92 We start by connecting to the `connected()` signal.
93 \snippet echoclient/echoclient.cpp constructor
94 After the connection, we open the socket to the given \a url.
96 \snippet echoclient/echoclient.cpp onConnected
97 When the client is connected successfully, we connect to the `onTextMessageReceived()` signal,
98 and send out "Hello, world!".
99 If connected with the EchoServer, we will receive the same message back.
101 \snippet echoclient/echoclient.cpp onTextMessageReceived
102 Whenever a message is received, we write it out.
106 \fn void QWebSocket::connected()
107 \brief Emitted when a connection is successfully established.
108 A connection is successfully established when the socket is connected
109 and the handshake was successful.
110 \sa open(), disconnected()
113 \fn void QWebSocket::disconnected()
114 \brief Emitted when the socket is disconnected.
115 \sa close(), connected()
118 \fn void QWebSocket::aboutToClose()
120 This signal is emitted when the socket is about to close.
121 Connect this signal if you have operations that need to be performed before the socket closes
122 (e.g., if you have data in a separate buffer that needs to be written to the device).
127 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
129 This signal can be emitted when a \a proxy that requires
130 authentication is used. The \a authenticator object can then be
131 filled in with the required details to allow authentication and
132 continue the connection.
134 \note It is not possible to use a QueuedConnection to connect to
135 this signal, as the connection will fail if the authenticator has
136 not been filled in with new information when the signal returns.
138 \sa QAuthenticator, QNetworkProxy
141 \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
143 This signal is emitted whenever QWebSocket's state changes.
144 The \a state parameter is the new state.
146 \note QAbstractSocket::ConnectedState is emitted after the handshake
147 with the server has succeeded.
149 QAbstractSocket::SocketState is not a registered metatype, so for queued
150 connections, you will have to register it with Q_REGISTER_METATYPE() and
156 \fn void QWebSocket::readChannelFinished()
158 This signal is emitted when the input (reading) stream is closed in this device.
159 It is emitted as soon as the closing is detected.
164 \fn void QWebSocket::bytesWritten(qint64 bytes)
166 This signal is emitted every time a payload of data has been written to the socket.
167 The \a bytes argument is set to the number of bytes that were written in this payload.
169 \note This signal has the same meaning both for secure and non-secure WebSockets.
170 As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively
171 written (see QSslSocket::encryptedBytesWritten()).
176 \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
178 This signal is emitted whenever a text frame is received. The \a frame contains the data and
179 \a isLastFrame indicates whether this is the last frame of the complete message.
181 This signal can be used to process large messages frame by frame, instead of waiting for the
182 complete message to arrive.
184 \sa binaryFrameReceived()
187 \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
189 This signal is emitted whenever a binary frame is received. The \a frame contains the data and
190 \a isLastFrame indicates whether this is the last frame of the complete message.
192 This signal can be used to process large messages frame by frame, instead of waiting for the
193 complete message to arrive.
195 \sa textFrameReceived()
198 \fn void QWebSocket::textMessageReceived(const QString &message);
200 This signal is emitted whenever a text message is received. The \a message contains the
203 \sa binaryMessageReceived()
206 \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
208 This signal is emitted whenever a binary message is received. The \a message contains the
211 \sa textMessageReceived()
214 \fn void QWebSocket::error(QAbstractSocket::SocketError error);
216 This signal is emitted after an error occurred. The \a error
217 parameter describes the type of error that occurred.
219 QAbstractSocket::SocketError is not a registered metatype, so for queued
220 connections, you will have to register it with Q_DECLARE_METATYPE() and
223 \sa error(), errorString()
226 \fn void QWebSocket::sslErrors(const QList<QSslError> &errors)
227 QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have
228 occurred while establishing the identity of the peer.
229 The errors are usually an indication that QWebSocket is unable to securely identify the peer.
230 Unless any action is taken, the connection will be dropped after this signal has been emitted.
231 If you want to continue connecting despite the errors that have occurred, you must call
232 QWebSocket::ignoreSslErrors() from inside a slot connected to this signal.
233 If you need to access the error list at a later point, you can call sslErrors()
236 \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
239 \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
240 QWebSocket::ignoreSslErrors() will have no effect.
243 \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
245 Emitted when a pong message is received in reply to a previous ping.
246 \a elapsedTime contains the roundtrip time in milliseconds and \a payload contains an optional
247 payload that was sent with the ping.
251 #include "qwebsocket.h"
252 #include "qwebsocket_p.h"
254 #include <QtCore/QUrl>
255 #include <QtNetwork/QTcpSocket>
256 #include <QtCore/QByteArray>
257 #include <QtNetwork/QHostAddress>
259 #include <QtCore/QDebug>
266 * \brief Creates a new QWebSocket with the given \a origin,
267 * the \a version of the protocol to use and \a parent.
269 * The \a origin of the client is as specified in \l {http://tools.ietf.org/html/rfc6454}{RFC 6454}.
270 * (The \a origin is not required for non-web browser clients
271 * (see \l {http://tools.ietf.org/html/rfc6455}{RFC 6455})).
272 * The \a origin may not contain new line characters, otherwise the connection will be
273 * aborted immediately during the handshake phase.
274 * \note Currently only V13 (\l {http://tools.ietf.org/html/rfc6455} {RFC 6455}) is supported
276 QWebSocket::QWebSocket(const QString &origin,
277 QWebSocketProtocol::Version version,
279 QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
286 * \brief Destroys the QWebSocket. Closes the socket if it is still open,
287 * and releases any used resources.
289 QWebSocket::~QWebSocket()
294 * \brief Aborts the current socket and resets the socket.
295 * Unlike close(), this function immediately closes the socket,
296 * discarding any pending data in the write buffer.
298 void QWebSocket::abort()
305 * Returns the type of error that last occurred
308 QAbstractSocket::SocketError QWebSocket::error() const
310 Q_D(const QWebSocket);
314 //only called by QWebSocketPrivate::upgradeFrom
318 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
319 QWebSocketProtocol::Version version, QObject *parent) :
320 QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
327 * Returns a human-readable description of the last error that occurred
331 QString QWebSocket::errorString() const
333 Q_D(const QWebSocket);
334 return d->errorString();
338 This function writes as much as possible from the internal write buffer
339 to the underlying network socket, without blocking.
340 If any data was written, this function returns true; otherwise false is returned.
341 Call this function if you need QWebSocket to start sending buffered data immediately.
342 The number of bytes successfully written depends on the operating system.
343 In most cases, you do not need to call this function,
344 because QWebSocket will start sending data automatically
345 once control goes back to the event loop.
347 bool QWebSocket::flush()
354 \brief Sends the given \a message over the socket as a text message and
355 returns the number of bytes actually sent.
357 \sa sendBinaryMessage()
359 qint64 QWebSocket::sendTextMessage(const QString &message)
362 return d->sendTextMessage(message);
366 \brief Sends the given \a data over the socket as a binary message and
367 returns the number of bytes actually sent.
369 \sa sendTextMessage()
371 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
374 return d->sendBinaryMessage(data);
378 \brief Gracefully closes the socket with the given \a closeCode and \a reason.
380 Any data in the write buffer is flushed before the socket is closed.
381 The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
382 \a reason describes the reason of the closure more in detail
384 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
387 d->close(closeCode, reason);
391 \brief Opens a WebSocket connection using the given \a url.
393 If the url contains newline characters (\\r\\n), then the error signal will be emitted
394 with QAbstractSocket::ConnectionRefusedError as error type.
396 void QWebSocket::open(const QUrl &url)
403 \brief Pings the server to indicate that the connection is still alive.
404 Additional \a payload can be sent along the ping message.
406 The size of the \a payload cannot be bigger than 125.
407 If it is larger, the \a payload is clipped to 125 bytes.
411 void QWebSocket::ping(const QByteArray &payload)
419 This slot tells QWebSocket to ignore errors during QWebSocket's
420 handshake phase and continue connecting. If you want to continue
421 with the connection even if errors occur during the handshake
422 phase, then you must call this slot, either from a slot connected
423 to sslErrors(), or before the handshake phase. If you don't call
424 this slot, either in response to errors or before the handshake,
425 the connection will be dropped after the sslErrors() signal has
428 \warning Be sure to always let the user inspect the errors
429 reported by the sslErrors() signal, and only call this method
430 upon confirmation from the user that proceeding is ok.
431 If there are unexpected errors, the connection should be aborted.
432 Calling this method without inspecting the actual errors will
433 most likely pose a security risk for your application. Use it
436 \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
438 void QWebSocket::ignoreSslErrors()
441 d->ignoreSslErrors();
447 This method tells QWebSocket to ignore the errors given in \a errors.
449 Note that you can set the expected certificate in the SSL error:
450 If, for instance, you want to connect to a server that uses
451 a self-signed certificate, consider the following snippet:
453 \snippet src_websockets_ssl_qwebsocket.cpp 6
455 Multiple calls to this function will replace the list of errors that
456 were passed in previous calls.
457 You can clear the list of errors you want to ignore by calling this
458 function with an empty list.
462 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
465 d->ignoreSslErrors(errors);
469 Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
471 This function sets the local certificate, the ciphers, the private key and
472 the CA certificates to those stored in \a sslConfiguration.
473 It is not possible to set the SSL-state related fields.
474 \sa sslConfiguration()
476 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
479 d->setSslConfiguration(sslConfiguration);
483 Returns the socket's SSL configuration state.
484 The default SSL configuration of a socket is to use the default ciphers,
485 default CA certificates, no local private key or certificate.
486 The SSL configuration also contains fields that can change with time without notice.
488 \sa setSslConfiguration()
490 QSslConfiguration QWebSocket::sslConfiguration() const
492 Q_D(const QWebSocket);
493 return d->sslConfiguration();
496 #endif //not QT_NO_SSL
499 \brief Returns the version the socket is currently using.
501 QWebSocketProtocol::Version QWebSocket::version() const
503 Q_D(const QWebSocket);
508 \brief Returns the name of the resource currently accessed.
510 QString QWebSocket::resourceName() const
512 Q_D(const QWebSocket);
513 return d->resourceName();
517 \brief Returns the url the socket is connected to or will connect to.
519 QUrl QWebSocket::requestUrl() const
521 Q_D(const QWebSocket);
522 return d->requestUrl();
526 \brief Returns the current origin.
528 QString QWebSocket::origin() const
530 Q_D(const QWebSocket);
535 \brief Returns the code indicating why the socket was closed.
536 \sa QWebSocketProtocol::CloseCode, closeReason()
538 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
540 Q_D(const QWebSocket);
541 return d->closeCode();
545 \brief Returns the reason why the socket was closed.
548 QString QWebSocket::closeReason() const
550 Q_D(const QWebSocket);
551 return d->closeReason();
555 \brief Returns the current state of the socket.
557 QAbstractSocket::SocketState QWebSocket::state() const
559 Q_D(const QWebSocket);
564 Returns the local address
566 QHostAddress QWebSocket::localAddress() const
568 Q_D(const QWebSocket);
569 return d->localAddress();
573 Returns the local port
575 quint16 QWebSocket::localPort() const
577 Q_D(const QWebSocket);
578 return d->localPort();
582 Returns the pause mode of this socket
584 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
586 Q_D(const QWebSocket);
587 return d->pauseMode();
591 Returns the peer address
593 QHostAddress QWebSocket::peerAddress() const
595 Q_D(const QWebSocket);
596 return d->peerAddress();
602 QString QWebSocket::peerName() const
604 Q_D(const QWebSocket);
605 return d->peerName();
611 quint16 QWebSocket::peerPort() const
613 Q_D(const QWebSocket);
614 return d->peerPort();
617 #ifndef QT_NO_NETWORKPROXY
619 Returns the currently configured proxy
621 QNetworkProxy QWebSocket::proxy() const
623 Q_D(const QWebSocket);
628 Sets the proxy to \a networkProxy
630 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
633 d->setProxy(networkProxy);
638 Sets the generator to use for creating masks to \a maskGenerator.
639 The default QWebSocket generator can be reset by supplying a \e Q_NULLPTR.
640 The mask generator can be changed at any time, even while the connection is open.
642 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
645 d->setMaskGenerator(maskGenerator);
649 Returns the mask generator that is currently used by this QWebSocket.
651 const QMaskGenerator *QWebSocket::maskGenerator() const
653 Q_D(const QWebSocket);
654 return d->maskGenerator();
658 Returns the size in bytes of the readbuffer that is used by the socket.
660 qint64 QWebSocket::readBufferSize() const
662 Q_D(const QWebSocket);
663 return d->readBufferSize();
667 Continues data transfer on the socket. This method should only be used after the socket
668 has been set to pause upon notifications and a notification has been received.
669 The only notification currently supported is sslErrors().
670 Calling this method if the socket is not paused results in undefined behavior.
672 \sa pauseMode(), setPauseMode()
674 void QWebSocket::resume()
681 Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
682 the conditions in which the socket should be paused.
684 The only notification currently supported is sslErrors().
685 If set to PauseOnSslErrors, data transfer on the socket will be paused
686 and needs to be enabled explicitly again by calling resume().
687 By default, this option is set to PauseNever. This option must be called
688 before connecting to the server, otherwise it will result in undefined behavior.
690 \sa pauseMode(), resume()
692 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
695 d->setPauseMode(pauseMode);
699 Sets the size of QWebSocket's internal read buffer to be \a size bytes.
701 If the buffer size is limited to a certain size, QWebSocket won't buffer more than
703 Exceptionally, a buffer size of 0 means that the read buffer is unlimited and
704 all incoming data is buffered. This is the default.
705 This option is useful if you only read the data at certain points in time
706 (for example, in a real-time streaming application) or if you want to protect your socket against
707 receiving too much data, which may eventually cause your application to run out of memory.
711 void QWebSocket::setReadBufferSize(qint64 size)
714 d->setReadBufferSize(size);
718 Returns \c true if the socket is ready for reading and writing; otherwise
721 bool QWebSocket::isValid() const
723 Q_D(const QWebSocket);