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: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.
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.
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.
32 ****************************************************************************/
37 \inmodule QtWebSockets
38 \brief Implements a TCP socket that talks the WebSocket protocol.
40 WebSockets is a web technology providing full-duplex communications channels over
41 a single TCP connection.
42 The WebSocket protocol was standardized by the IETF as
43 \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
44 QWebSocket can both be used in a client application and server application.
46 This class was modeled after QAbstractSocket.
48 QWebSocket currently does not support
49 \l {http://tools.ietf.org/html/rfc6455#page-39} {extensions} and
50 \l {http://tools.ietf.org/html/rfc6455#page-12} {subprotocols}.
52 QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
53 \l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
55 \note Some proxies do not understand certain HTTP headers used during a WebSocket handshake.
56 In that case, non-secure WebSocket connections fail. The best way to mitigate against
57 this problem is to use WebSocket over a secure connection.
59 \warning To generate masks, this implementation of WebSockets uses the cryptographically
60 insecure qrand() function.
61 For more information about the importance of good masking,
62 see \l {http://w2spconf.com/2011/papers/websocket.pdf}.
63 The best measure against attacks mentioned in the document above,
64 is to use QWebSocket over a secure connection (\e wss://).
65 In general, always be careful to not have 3rd party script access to
66 a QWebSocket in your application.
68 \sa QAbstractSocket, QTcpSocket
70 \sa {QWebSocket client example}
74 \page echoclient.html example
75 \title QWebSocket client example
76 \brief A sample WebSocket client that sends a message and displays the message that
80 The EchoClient example implements a WebSocket client that sends a message to a WebSocket server
81 and dumps the answer that it gets back.
82 This example should ideally be used with the EchoServer example.
84 We start by connecting to the `connected()` signal.
85 \snippet echoclient/echoclient.cpp constructor
86 After the connection, we open the socket to the given \a url.
88 \snippet echoclient/echoclient.cpp onConnected
89 When the client is connected successfully, we connect to the `onTextMessageReceived()` signal,
90 and send out "Hello, world!".
91 If connected with the EchoServer, we will receive the same message back.
93 \snippet echoclient/echoclient.cpp onTextMessageReceived
94 Whenever a message is received, we write it out.
98 \fn void QWebSocket::connected()
99 \brief Emitted when a connection is successfully established.
100 A connection is successfully established when the socket is connected
101 and the handshake was successful.
102 \sa open(), disconnected()
105 \fn void QWebSocket::disconnected()
106 \brief Emitted when the socket is disconnected.
107 \sa close(), connected()
110 \fn void QWebSocket::aboutToClose()
112 This signal is emitted when the socket is about to close.
113 Connect this signal if you have operations that need to be performed before the socket closes
114 (e.g., if you have data in a separate buffer that needs to be written to the device).
119 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
121 This signal can be emitted when a \a proxy that requires
122 authentication is used. The \a authenticator object can then be
123 filled in with the required details to allow authentication and
124 continue the connection.
126 \note It is not possible to use a QueuedConnection to connect to
127 this signal, as the connection will fail if the authenticator has
128 not been filled in with new information when the signal returns.
130 \sa QAuthenticator, QNetworkProxy
133 \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
135 This signal is emitted whenever QWebSocket's state changes.
136 The \a state parameter is the new state.
138 \note QAbstractSocket::ConnectedState is emitted after the handshake
139 with the server has succeeded.
141 QAbstractSocket::SocketState is not a registered metatype, so for queued
142 connections, you will have to register it with Q_REGISTER_METATYPE() and
148 \fn void QWebSocket::readChannelFinished()
150 This signal is emitted when the input (reading) stream is closed in this device.
151 It is emitted as soon as the closing is detected.
156 \fn void QWebSocket::bytesWritten(qint64 bytes)
158 This signal is emitted every time a payload of data has been written to the socket.
159 The \a bytes argument is set to the number of bytes that were written in this payload.
161 \note This signal has the same meaning both for secure and non-secure WebSockets.
162 As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively
163 written (see QSslSocket::encryptedBytesWritten()).
168 \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
170 This signal is emitted whenever a text frame is received. The \a frame contains the data and
171 \a isLastFrame indicates whether this is the last frame of the complete message.
173 This signal can be used to process large messages frame by frame, instead of waiting for the
174 complete message to arrive.
176 \sa binaryFrameReceived()
179 \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
181 This signal is emitted whenever a binary frame is received. The \a frame contains the data and
182 \a isLastFrame indicates whether this is the last frame of the complete message.
184 This signal can be used to process large messages frame by frame, instead of waiting for the
185 complete message to arrive.
187 \sa textFrameReceived()
190 \fn void QWebSocket::textMessageReceived(const QString &message);
192 This signal is emitted whenever a text message is received. The \a message contains the
195 \sa binaryMessageReceived()
198 \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
200 This signal is emitted whenever a binary message is received. The \a message contains the
203 \sa textMessageReceived()
206 \fn void QWebSocket::error(QAbstractSocket::SocketError error);
208 This signal is emitted after an error occurred. The \a error
209 parameter describes the type of error that occurred.
211 QAbstractSocket::SocketError is not a registered metatype, so for queued
212 connections, you will have to register it with Q_DECLARE_METATYPE() and
215 \sa error(), errorString()
218 \fn void QWebSocket::sslErrors(const QList<QSslError> &errors)
219 QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have
220 occurred while establishing the identity of the peer.
221 The errors are usually an indication that QWebSocket is unable to securely identify the peer.
222 Unless any action is taken, the connection will be dropped after this signal has been emitted.
223 If you want to continue connecting despite the errors that have occurred, you must call
224 QWebSocket::ignoreSslErrors() from inside a slot connected to this signal.
225 If you need to access the error list at a later point, you can call sslErrors()
228 \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
231 \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
232 QWebSocket::ignoreSslErrors() will have no effect.
235 \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
237 Emitted when a pong message is received in reply to a previous ping.
238 \a elapsedTime contains the roundtrip time in milliseconds and \a payload contains an optional
239 payload that was sent with the ping.
243 #include "qwebsocket.h"
244 #include "qwebsocket_p.h"
246 #include <QtCore/QUrl>
247 #include <QtNetwork/QTcpSocket>
248 #include <QtCore/QByteArray>
249 #include <QtNetwork/QHostAddress>
251 #include <QtCore/QDebug>
258 * \brief Creates a new QWebSocket with the given \a origin,
259 * the \a version of the protocol to use and \a parent.
261 * The \a origin of the client is as specified in \l {http://tools.ietf.org/html/rfc6454}{RFC 6454}.
262 * (The \a origin is not required for non-web browser clients
263 * (see \l {http://tools.ietf.org/html/rfc6455}{RFC 6455})).
264 * The \a origin may not contain new line characters, otherwise the connection will be
265 * aborted immediately during the handshake phase.
266 * \note Currently only V13 (\l {http://tools.ietf.org/html/rfc6455} {RFC 6455}) is supported
268 QWebSocket::QWebSocket(const QString &origin,
269 QWebSocketProtocol::Version version,
271 QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
278 * \brief Destroys the QWebSocket. Closes the socket if it is still open,
279 * and releases any used resources.
281 QWebSocket::~QWebSocket()
286 * \brief Aborts the current socket and resets the socket.
287 * Unlike close(), this function immediately closes the socket,
288 * discarding any pending data in the write buffer.
290 void QWebSocket::abort()
297 * Returns the type of error that last occurred
300 QAbstractSocket::SocketError QWebSocket::error() const
302 Q_D(const QWebSocket);
306 //only called by QWebSocketPrivate::upgradeFrom
310 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
311 QWebSocketProtocol::Version version, QObject *parent) :
312 QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
319 * Returns a human-readable description of the last error that occurred
323 QString QWebSocket::errorString() const
325 Q_D(const QWebSocket);
326 return d->errorString();
330 This function writes as much as possible from the internal write buffer
331 to the underlying network socket, without blocking.
332 If any data was written, this function returns true; otherwise false is returned.
333 Call this function if you need QWebSocket to start sending buffered data immediately.
334 The number of bytes successfully written depends on the operating system.
335 In most cases, you do not need to call this function,
336 because QWebSocket will start sending data automatically
337 once control goes back to the event loop.
339 bool QWebSocket::flush()
346 \brief Sends the given \a message over the socket as a text message and
347 returns the number of bytes actually sent.
349 \sa sendBinaryMessage()
351 qint64 QWebSocket::sendTextMessage(const QString &message)
354 return d->sendTextMessage(message);
358 \brief Sends the given \a data over the socket as a binary message and
359 returns the number of bytes actually sent.
361 \sa sendTextMessage()
363 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
366 return d->sendBinaryMessage(data);
370 \brief Gracefully closes the socket with the given \a closeCode and \a reason.
372 Any data in the write buffer is flushed before the socket is closed.
373 The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
374 \a reason describes the reason of the closure more in detail
376 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
379 d->close(closeCode, reason);
383 \brief Opens a WebSocket connection using the given \a url.
385 If the url contains newline characters (\\r\\n), then the error signal will be emitted
386 with QAbstractSocket::ConnectionRefusedError as error type.
388 void QWebSocket::open(const QUrl &url)
395 \brief Pings the server to indicate that the connection is still alive.
396 Additional \a payload can be sent along the ping message.
398 The size of the \a payload cannot be bigger than 125.
399 If it is larger, the \a payload is clipped to 125 bytes.
403 void QWebSocket::ping(const QByteArray &payload)
411 This slot tells QWebSocket to ignore errors during QWebSocket's
412 handshake phase and continue connecting. If you want to continue
413 with the connection even if errors occur during the handshake
414 phase, then you must call this slot, either from a slot connected
415 to sslErrors(), or before the handshake phase. If you don't call
416 this slot, either in response to errors or before the handshake,
417 the connection will be dropped after the sslErrors() signal has
420 \warning Be sure to always let the user inspect the errors
421 reported by the sslErrors() signal, and only call this method
422 upon confirmation from the user that proceeding is ok.
423 If there are unexpected errors, the connection should be aborted.
424 Calling this method without inspecting the actual errors will
425 most likely pose a security risk for your application. Use it
428 \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
430 void QWebSocket::ignoreSslErrors()
433 d->ignoreSslErrors();
439 This method tells QWebSocket to ignore the errors given in \a errors.
441 Note that you can set the expected certificate in the SSL error:
442 If, for instance, you want to connect to a server that uses
443 a self-signed certificate, consider the following snippet:
445 \snippet src_websockets_ssl_qwebsocket.cpp 6
447 Multiple calls to this function will replace the list of errors that
448 were passed in previous calls.
449 You can clear the list of errors you want to ignore by calling this
450 function with an empty list.
454 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
457 d->ignoreSslErrors(errors);
461 Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
463 This function sets the local certificate, the ciphers, the private key and
464 the CA certificates to those stored in \a sslConfiguration.
465 It is not possible to set the SSL-state related fields.
466 \sa sslConfiguration()
468 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
471 d->setSslConfiguration(sslConfiguration);
475 Returns the socket's SSL configuration state.
476 The default SSL configuration of a socket is to use the default ciphers,
477 default CA certificates, no local private key or certificate.
478 The SSL configuration also contains fields that can change with time without notice.
480 \sa setSslConfiguration()
482 QSslConfiguration QWebSocket::sslConfiguration() const
484 Q_D(const QWebSocket);
485 return d->sslConfiguration();
488 #endif //not QT_NO_SSL
491 \brief Returns the version the socket is currently using.
493 QWebSocketProtocol::Version QWebSocket::version() const
495 Q_D(const QWebSocket);
500 \brief Returns the name of the resource currently accessed.
502 QString QWebSocket::resourceName() const
504 Q_D(const QWebSocket);
505 return d->resourceName();
509 \brief Returns the url the socket is connected to or will connect to.
511 QUrl QWebSocket::requestUrl() const
513 Q_D(const QWebSocket);
514 return d->requestUrl();
518 \brief Returns the current origin.
520 QString QWebSocket::origin() const
522 Q_D(const QWebSocket);
527 \brief Returns the code indicating why the socket was closed.
528 \sa QWebSocketProtocol::CloseCode, closeReason()
530 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
532 Q_D(const QWebSocket);
533 return d->closeCode();
537 \brief Returns the reason why the socket was closed.
540 QString QWebSocket::closeReason() const
542 Q_D(const QWebSocket);
543 return d->closeReason();
547 \brief Returns the current state of the socket.
549 QAbstractSocket::SocketState QWebSocket::state() const
551 Q_D(const QWebSocket);
556 Returns the local address
558 QHostAddress QWebSocket::localAddress() const
560 Q_D(const QWebSocket);
561 return d->localAddress();
565 Returns the local port
567 quint16 QWebSocket::localPort() const
569 Q_D(const QWebSocket);
570 return d->localPort();
574 Returns the pause mode of this socket
576 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
578 Q_D(const QWebSocket);
579 return d->pauseMode();
583 Returns the peer address
585 QHostAddress QWebSocket::peerAddress() const
587 Q_D(const QWebSocket);
588 return d->peerAddress();
594 QString QWebSocket::peerName() const
596 Q_D(const QWebSocket);
597 return d->peerName();
603 quint16 QWebSocket::peerPort() const
605 Q_D(const QWebSocket);
606 return d->peerPort();
609 #ifndef QT_NO_NETWORKPROXY
611 Returns the currently configured proxy
613 QNetworkProxy QWebSocket::proxy() const
615 Q_D(const QWebSocket);
620 Sets the proxy to \a networkProxy
622 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
625 d->setProxy(networkProxy);
630 Sets the generator to use for creating masks to \a maskGenerator.
631 The default QWebSocket generator can be reset by supplying a \e Q_NULLPTR.
632 The mask generator can be changed at any time, even while the connection is open.
634 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
637 d->setMaskGenerator(maskGenerator);
641 Returns the mask generator that is currently used by this QWebSocket.
643 const QMaskGenerator *QWebSocket::maskGenerator() const
645 Q_D(const QWebSocket);
646 return d->maskGenerator();
650 Returns the size in bytes of the readbuffer that is used by the socket.
652 qint64 QWebSocket::readBufferSize() const
654 Q_D(const QWebSocket);
655 return d->readBufferSize();
659 Continues data transfer on the socket. This method should only be used after the socket
660 has been set to pause upon notifications and a notification has been received.
661 The only notification currently supported is sslErrors().
662 Calling this method if the socket is not paused results in undefined behavior.
664 \sa pauseMode(), setPauseMode()
666 void QWebSocket::resume()
673 Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
674 the conditions in which the socket should be paused.
676 The only notification currently supported is sslErrors().
677 If set to PauseOnSslErrors, data transfer on the socket will be paused
678 and needs to be enabled explicitly again by calling resume().
679 By default, this option is set to PauseNever. This option must be called
680 before connecting to the server, otherwise it will result in undefined behavior.
682 \sa pauseMode(), resume()
684 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
687 d->setPauseMode(pauseMode);
691 Sets the size of QWebSocket's internal read buffer to be \a size bytes.
693 If the buffer size is limited to a certain size, QWebSocket won't buffer more than
695 Exceptionally, a buffer size of 0 means that the read buffer is unlimited and
696 all incoming data is buffered. This is the default.
697 This option is useful if you only read the data at certain points in time
698 (for example, in a real-time streaming application) or if you want to protect your socket against
699 receiving too much data, which may eventually cause your application to run out of memory.
703 void QWebSocket::setReadBufferSize(qint64 size)
706 d->setReadBufferSize(size);
710 Returns \c true if the socket is ready for reading and writing; otherwise
713 bool QWebSocket::isValid() const
715 Q_D(const QWebSocket);