Update license headers and add new license files
[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     \brief Implements a TCP socket that talks the WebSocket protocol.
39
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.
45
46     This class was modeled after QAbstractSocket.
47
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}.
51
52     QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
53     \l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
54
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.
58
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.
67
68     \sa QAbstractSocket, QTcpSocket
69
70     \sa {QWebSocket client example}
71 */
72
73 /*!
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
77     it receives back.
78
79     \section1 Description
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.
83     \section1 Code
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.
87
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.
92
93     \snippet echoclient/echoclient.cpp onTextMessageReceived
94     Whenever a message is received, we write it out.
95 */
96
97 /*!
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()
103 */
104 /*!
105   \fn void QWebSocket::disconnected()
106   \brief Emitted when the socket is disconnected.
107   \sa close(), connected()
108 */
109 /*!
110     \fn void QWebSocket::aboutToClose()
111
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).
115
116     \sa close()
117  */
118 /*!
119 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
120
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.
125
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.
129
130 \sa QAuthenticator, QNetworkProxy
131 */
132 /*!
133     \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
134
135     This signal is emitted whenever QWebSocket's state changes.
136     The \a state parameter is the new state.
137
138     \note QAbstractSocket::ConnectedState is emitted after the handshake
139     with the server has succeeded.
140
141     QAbstractSocket::SocketState is not a registered metatype, so for queued
142     connections, you will have to register it with Q_REGISTER_METATYPE() and
143     qRegisterMetaType().
144
145     \sa state()
146 */
147 /*!
148     \fn void QWebSocket::readChannelFinished()
149
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.
152
153     \sa close()
154 */
155 /*!
156     \fn void QWebSocket::bytesWritten(qint64 bytes)
157
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.
160
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()).
164     \sa close()
165 */
166
167 /*!
168     \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
169
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.
172
173     This signal can be used to process large messages frame by frame, instead of waiting for the
174     complete message to arrive.
175
176     \sa binaryFrameReceived()
177 */
178 /*!
179     \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
180
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.
183
184     This signal can be used to process large messages frame by frame, instead of waiting for the
185     complete message to arrive.
186
187     \sa textFrameReceived()
188 */
189 /*!
190     \fn void QWebSocket::textMessageReceived(const QString &message);
191
192     This signal is emitted whenever a text message is received. The \a message contains the
193     received text.
194
195     \sa binaryMessageReceived()
196 */
197 /*!
198     \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
199
200     This signal is emitted whenever a binary message is received. The \a message contains the
201     received bytes.
202
203     \sa textMessageReceived()
204 */
205 /*!
206     \fn void QWebSocket::error(QAbstractSocket::SocketError error);
207
208     This signal is emitted after an error occurred. The \a error
209     parameter describes the type of error that occurred.
210
211     QAbstractSocket::SocketError is not a registered metatype, so for queued
212     connections, you will have to register it with Q_DECLARE_METATYPE() and
213     qRegisterMetaType().
214
215     \sa error(), errorString()
216 */
217 /*!
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()
226     (without arguments).
227
228     \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
229     the peer.
230
231     \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
232     QWebSocket::ignoreSslErrors() will have no effect.
233 */
234 /*!
235     \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
236
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.
240
241     \sa ping()
242   */
243 #include "qwebsocket.h"
244 #include "qwebsocket_p.h"
245
246 #include <QtCore/QUrl>
247 #include <QtNetwork/QTcpSocket>
248 #include <QtCore/QByteArray>
249 #include <QtNetwork/QHostAddress>
250
251 #include <QtCore/QDebug>
252
253 #include <limits>
254
255 QT_BEGIN_NAMESPACE
256
257 /*!
258  * \brief Creates a new QWebSocket with the given \a origin,
259  * the \a version of the protocol to use and \a parent.
260  *
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
267  */
268 QWebSocket::QWebSocket(const QString &origin,
269                        QWebSocketProtocol::Version version,
270                        QObject *parent) :
271     QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
272 {
273     Q_D(QWebSocket);
274     d->init();
275 }
276
277 /*!
278  * \brief Destroys the QWebSocket. Closes the socket if it is still open,
279  * and releases any used resources.
280  */
281 QWebSocket::~QWebSocket()
282 {
283 }
284
285 /*!
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.
289  */
290 void QWebSocket::abort()
291 {
292     Q_D(QWebSocket);
293     d->abort();
294 }
295
296 /*!
297  * Returns the type of error that last occurred
298  * \sa errorString()
299  */
300 QAbstractSocket::SocketError QWebSocket::error() const
301 {
302     Q_D(const QWebSocket);
303     return d->error();
304 }
305
306 //only called by QWebSocketPrivate::upgradeFrom
307 /*!
308   \internal
309  */
310 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
311                        QWebSocketProtocol::Version version, QObject *parent) :
312     QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
313 {
314     Q_D(QWebSocket);
315     d->init();
316 }
317
318 /*!
319  * Returns a human-readable description of the last error that occurred
320  *
321  * \sa error()
322  */
323 QString QWebSocket::errorString() const
324 {
325     Q_D(const QWebSocket);
326     return d->errorString();
327 }
328
329 /*!
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.
338 */
339 bool QWebSocket::flush()
340 {
341     Q_D(QWebSocket);
342     return d->flush();
343 }
344
345 /*!
346     \brief Sends the given \a message over the socket as a text message and
347     returns the number of bytes actually sent.
348
349     \sa sendBinaryMessage()
350  */
351 qint64 QWebSocket::sendTextMessage(const QString &message)
352 {
353     Q_D(QWebSocket);
354     return d->sendTextMessage(message);
355 }
356
357 /*!
358     \brief Sends the given \a data over the socket as a binary message and
359     returns the number of bytes actually sent.
360
361     \sa sendTextMessage()
362  */
363 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
364 {
365     Q_D(QWebSocket);
366     return d->sendBinaryMessage(data);
367 }
368
369 /*!
370     \brief Gracefully closes the socket with the given \a closeCode and \a reason.
371
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
375  */
376 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
377 {
378     Q_D(QWebSocket);
379     d->close(closeCode, reason);
380 }
381
382 /*!
383     \brief Opens a WebSocket connection using the given \a url.
384
385     If the url contains newline characters (\\r\\n), then the error signal will be emitted
386     with QAbstractSocket::ConnectionRefusedError as error type.
387  */
388 void QWebSocket::open(const QUrl &url)
389 {
390     Q_D(QWebSocket);
391     d->open(url, true);
392 }
393
394 /*!
395     \brief Pings the server to indicate that the connection is still alive.
396     Additional \a payload can be sent along the ping message.
397
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.
400
401     \sa pong()
402  */
403 void QWebSocket::ping(const QByteArray &payload)
404 {
405     Q_D(QWebSocket);
406     d->ping(payload);
407 }
408
409 #ifndef QT_NO_SSL
410 /*!
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
418     been emitted.
419
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
426     with great care!
427
428     \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
429 */
430 void QWebSocket::ignoreSslErrors()
431 {
432     Q_D(QWebSocket);
433     d->ignoreSslErrors();
434 }
435
436 /*!
437     \overload
438
439     This method tells QWebSocket to ignore the errors given in \a errors.
440
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:
444
445     \snippet src_websockets_ssl_qwebsocket.cpp 6
446
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.
451
452     \sa sslErrors()
453 */
454 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
455 {
456     Q_D(QWebSocket);
457     d->ignoreSslErrors(errors);
458 }
459
460 /*!
461     Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
462
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()
467  */
468 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
469 {
470     Q_D(QWebSocket);
471     d->setSslConfiguration(sslConfiguration);
472 }
473
474 /*!
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.
479
480     \sa setSslConfiguration()
481  */
482 QSslConfiguration QWebSocket::sslConfiguration() const
483 {
484     Q_D(const QWebSocket);
485     return d->sslConfiguration();
486 }
487
488 #endif  //not QT_NO_SSL
489
490 /*!
491     \brief Returns the version the socket is currently using.
492  */
493 QWebSocketProtocol::Version QWebSocket::version() const
494 {
495     Q_D(const QWebSocket);
496     return d->version();
497 }
498
499 /*!
500     \brief Returns the name of the resource currently accessed.
501  */
502 QString QWebSocket::resourceName() const
503 {
504     Q_D(const QWebSocket);
505     return d->resourceName();
506 }
507
508 /*!
509     \brief Returns the url the socket is connected to or will connect to.
510  */
511 QUrl QWebSocket::requestUrl() const
512 {
513     Q_D(const QWebSocket);
514     return d->requestUrl();
515 }
516
517 /*!
518     \brief Returns the current origin.
519  */
520 QString QWebSocket::origin() const
521 {
522     Q_D(const QWebSocket);
523     return d->origin();
524 }
525
526 /*!
527     \brief Returns the code indicating why the socket was closed.
528     \sa QWebSocketProtocol::CloseCode, closeReason()
529  */
530 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
531 {
532     Q_D(const QWebSocket);
533     return d->closeCode();
534 }
535
536 /*!
537     \brief Returns the reason why the socket was closed.
538     \sa closeCode()
539  */
540 QString QWebSocket::closeReason() const
541 {
542     Q_D(const QWebSocket);
543     return d->closeReason();
544 }
545
546 /*!
547     \brief Returns the current state of the socket.
548  */
549 QAbstractSocket::SocketState QWebSocket::state() const
550 {
551     Q_D(const QWebSocket);
552     return d->state();
553 }
554
555 /*!
556     Returns the local address
557  */
558 QHostAddress QWebSocket::localAddress() const
559 {
560     Q_D(const QWebSocket);
561     return d->localAddress();
562 }
563
564 /*!
565     Returns the local port
566  */
567 quint16 QWebSocket::localPort() const
568 {
569     Q_D(const QWebSocket);
570     return d->localPort();
571 }
572
573 /*!
574     Returns the pause mode of this socket
575  */
576 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
577 {
578     Q_D(const QWebSocket);
579     return d->pauseMode();
580 }
581
582 /*!
583     Returns the peer address
584  */
585 QHostAddress QWebSocket::peerAddress() const
586 {
587     Q_D(const QWebSocket);
588     return d->peerAddress();
589 }
590
591 /*!
592     Returns the peerName
593  */
594 QString QWebSocket::peerName() const
595 {
596     Q_D(const QWebSocket);
597     return d->peerName();
598 }
599
600 /*!
601     Returns the peerport
602  */
603 quint16 QWebSocket::peerPort() const
604 {
605     Q_D(const QWebSocket);
606     return d->peerPort();
607 }
608
609 #ifndef QT_NO_NETWORKPROXY
610 /*!
611     Returns the currently configured proxy
612  */
613 QNetworkProxy QWebSocket::proxy() const
614 {
615     Q_D(const QWebSocket);
616     return d->proxy();
617 }
618
619 /*!
620     Sets the proxy to \a networkProxy
621  */
622 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
623 {
624     Q_D(QWebSocket);
625     d->setProxy(networkProxy);
626 }
627 #endif
628
629 /*!
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.
633  */
634 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
635 {
636     Q_D(QWebSocket);
637     d->setMaskGenerator(maskGenerator);
638 }
639
640 /*!
641     Returns the mask generator that is currently used by this QWebSocket.
642  */
643 const QMaskGenerator *QWebSocket::maskGenerator() const
644 {
645     Q_D(const QWebSocket);
646     return d->maskGenerator();
647 }
648
649 /*!
650     Returns the size in bytes of the readbuffer that is used by the socket.
651  */
652 qint64 QWebSocket::readBufferSize() const
653 {
654     Q_D(const QWebSocket);
655     return d->readBufferSize();
656 }
657
658 /*!
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.
663
664     \sa pauseMode(), setPauseMode()
665  */
666 void QWebSocket::resume()
667 {
668     Q_D(QWebSocket);
669     d->resume();
670 }
671
672 /*!
673     Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
674     the conditions in which the socket should be paused.
675
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.
681
682     \sa pauseMode(), resume()
683  */
684 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
685 {
686     Q_D(QWebSocket);
687     d->setPauseMode(pauseMode);
688 }
689
690 /*!
691     Sets the size of QWebSocket's internal read buffer to be \a size bytes.
692
693     If the buffer size is limited to a certain size, QWebSocket won't buffer more than
694     this size of data.
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.
700
701     \sa readBufferSize()
702 */
703 void QWebSocket::setReadBufferSize(qint64 size)
704 {
705     Q_D(QWebSocket);
706     d->setReadBufferSize(size);
707 }
708
709 /*!
710     Returns \c true if the socket is ready for reading and writing; otherwise
711     returns \c false.
712  */
713 bool QWebSocket::isValid() const
714 {
715     Q_D(const QWebSocket);
716     return d->isValid();
717 }
718
719 QT_END_NAMESPACE