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
39 \brief Implements a TCP socket that talks the WebSocket protocol.
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.
47 This class was modeled after QAbstractSocket.
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}.
53 QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
54 \l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
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.
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.
69 \sa QAbstractSocket, QTcpSocket
71 \sa {QWebSocket client example}
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
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.
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.
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.
94 \snippet echoclient/echoclient.cpp onTextMessageReceived
95 Whenever a message is received, we write it out.
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()
106 \fn void QWebSocket::disconnected()
107 \brief Emitted when the socket is disconnected.
108 \sa close(), connected()
111 \fn void QWebSocket::aboutToClose()
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).
120 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
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.
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.
131 \sa QAuthenticator, QNetworkProxy
134 \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
136 This signal is emitted whenever QWebSocket's state changes.
137 The \a state parameter is the new state.
139 \note QAbstractSocket::ConnectedState is emitted after the handshake
140 with the server has succeeded.
142 QAbstractSocket::SocketState is not a registered metatype, so for queued
143 connections, you will have to register it with Q_REGISTER_METATYPE() and
149 \fn void QWebSocket::readChannelFinished()
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.
157 \fn void QWebSocket::bytesWritten(qint64 bytes)
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.
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()).
169 \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
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.
174 This signal can be used to process large messages frame by frame, instead of waiting for the
175 complete message to arrive.
177 \sa binaryFrameReceived()
180 \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
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.
185 This signal can be used to process large messages frame by frame, instead of waiting for the
186 complete message to arrive.
188 \sa textFrameReceived()
191 \fn void QWebSocket::textMessageReceived(const QString &message);
193 This signal is emitted whenever a text message is received. The \a message contains the
196 \sa binaryMessageReceived()
199 \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
201 This signal is emitted whenever a binary message is received. The \a message contains the
204 \sa textMessageReceived()
207 \fn void QWebSocket::error(QAbstractSocket::SocketError error);
209 This signal is emitted after an error occurred. The \a error
210 parameter describes the type of error that occurred.
212 QAbstractSocket::SocketError is not a registered metatype, so for queued
213 connections, you will have to register it with Q_DECLARE_METATYPE() and
216 \sa error(), errorString()
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()
229 \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
232 \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
233 QWebSocket::ignoreSslErrors() will have no effect.
236 \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
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.
244 #include "qwebsocket.h"
245 #include "qwebsocket_p.h"
247 #include <QtCore/QUrl>
248 #include <QtNetwork/QTcpSocket>
249 #include <QtCore/QByteArray>
250 #include <QtNetwork/QHostAddress>
252 #include <QtCore/QDebug>
259 * \brief Creates a new QWebSocket with the given \a origin,
260 * the \a version of the protocol to use and \a parent.
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
269 QWebSocket::QWebSocket(const QString &origin,
270 QWebSocketProtocol::Version version,
272 QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
279 * \brief Destroys the QWebSocket. Closes the socket if it is still open,
280 * and releases any used resources.
282 QWebSocket::~QWebSocket()
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.
291 void QWebSocket::abort()
298 * Returns the type of error that last occurred
301 QAbstractSocket::SocketError QWebSocket::error() const
303 Q_D(const QWebSocket);
307 //only called by QWebSocketPrivate::upgradeFrom
311 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
312 QWebSocketProtocol::Version version, QObject *parent) :
313 QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
320 * Returns a human-readable description of the last error that occurred
324 QString QWebSocket::errorString() const
326 Q_D(const QWebSocket);
327 return d->errorString();
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.
340 bool QWebSocket::flush()
347 \brief Sends the given \a message over the socket as a text message and
348 returns the number of bytes actually sent.
350 \sa sendBinaryMessage()
352 qint64 QWebSocket::sendTextMessage(const QString &message)
355 return d->sendTextMessage(message);
359 \brief Sends the given \a data over the socket as a binary message and
360 returns the number of bytes actually sent.
362 \sa sendTextMessage()
364 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
367 return d->sendBinaryMessage(data);
371 \brief Gracefully closes the socket with the given \a closeCode and \a reason.
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
377 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
380 d->close(closeCode, reason);
384 \brief Opens a WebSocket connection using the given \a url.
386 If the url contains newline characters (\\r\\n), then the error signal will be emitted
387 with QAbstractSocket::ConnectionRefusedError as error type.
389 void QWebSocket::open(const QUrl &url)
396 \brief Pings the server to indicate that the connection is still alive.
397 Additional \a payload can be sent along the ping message.
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.
404 void QWebSocket::ping(const QByteArray &payload)
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
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
429 \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
431 void QWebSocket::ignoreSslErrors()
434 d->ignoreSslErrors();
440 This method tells QWebSocket to ignore the errors given in \a errors.
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:
446 \snippet src_websockets_ssl_qwebsocket.cpp 6
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.
455 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
458 d->ignoreSslErrors(errors);
462 Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
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()
469 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
472 d->setSslConfiguration(sslConfiguration);
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.
481 \sa setSslConfiguration()
483 QSslConfiguration QWebSocket::sslConfiguration() const
485 Q_D(const QWebSocket);
486 return d->sslConfiguration();
489 #endif //not QT_NO_SSL
492 \brief Returns the version the socket is currently using.
494 QWebSocketProtocol::Version QWebSocket::version() const
496 Q_D(const QWebSocket);
501 \brief Returns the name of the resource currently accessed.
503 QString QWebSocket::resourceName() const
505 Q_D(const QWebSocket);
506 return d->resourceName();
510 \brief Returns the url the socket is connected to or will connect to.
512 QUrl QWebSocket::requestUrl() const
514 Q_D(const QWebSocket);
515 return d->requestUrl();
519 \brief Returns the current origin.
521 QString QWebSocket::origin() const
523 Q_D(const QWebSocket);
528 \brief Returns the code indicating why the socket was closed.
529 \sa QWebSocketProtocol::CloseCode, closeReason()
531 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
533 Q_D(const QWebSocket);
534 return d->closeCode();
538 \brief Returns the reason why the socket was closed.
541 QString QWebSocket::closeReason() const
543 Q_D(const QWebSocket);
544 return d->closeReason();
548 \brief Returns the current state of the socket.
550 QAbstractSocket::SocketState QWebSocket::state() const
552 Q_D(const QWebSocket);
557 Returns the local address
559 QHostAddress QWebSocket::localAddress() const
561 Q_D(const QWebSocket);
562 return d->localAddress();
566 Returns the local port
568 quint16 QWebSocket::localPort() const
570 Q_D(const QWebSocket);
571 return d->localPort();
575 Returns the pause mode of this socket
577 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
579 Q_D(const QWebSocket);
580 return d->pauseMode();
584 Returns the peer address
586 QHostAddress QWebSocket::peerAddress() const
588 Q_D(const QWebSocket);
589 return d->peerAddress();
595 QString QWebSocket::peerName() const
597 Q_D(const QWebSocket);
598 return d->peerName();
604 quint16 QWebSocket::peerPort() const
606 Q_D(const QWebSocket);
607 return d->peerPort();
610 #ifndef QT_NO_NETWORKPROXY
612 Returns the currently configured proxy
614 QNetworkProxy QWebSocket::proxy() const
616 Q_D(const QWebSocket);
621 Sets the proxy to \a networkProxy
623 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
626 d->setProxy(networkProxy);
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.
635 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
638 d->setMaskGenerator(maskGenerator);
642 Returns the mask generator that is currently used by this QWebSocket.
644 const QMaskGenerator *QWebSocket::maskGenerator() const
646 Q_D(const QWebSocket);
647 return d->maskGenerator();
651 Returns the size in bytes of the readbuffer that is used by the socket.
653 qint64 QWebSocket::readBufferSize() const
655 Q_D(const QWebSocket);
656 return d->readBufferSize();
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.
665 \sa pauseMode(), setPauseMode()
667 void QWebSocket::resume()
674 Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
675 the conditions in which the socket should be paused.
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.
683 \sa pauseMode(), resume()
685 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
688 d->setPauseMode(pauseMode);
692 Sets the size of QWebSocket's internal read buffer to be \a size bytes.
694 If the buffer size is limited to a certain size, QWebSocket won't buffer more than
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.
704 void QWebSocket::setReadBufferSize(qint64 size)
707 d->setReadBufferSize(size);
711 Returns \c true if the socket is ready for reading and writing; otherwise
714 bool QWebSocket::isValid() const
716 Q_D(const QWebSocket);