Use the proper protocol names
[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: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.
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 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.
24 **
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.
28 **
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.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 /*!
43     \class QWebSocket
44
45     \inmodule QtWebSockets
46     \brief Implements a TCP socket that talks the WebSocket protocol.
47
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.
53
54     This class was modeled after QAbstractSocket.
55
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}.
59
60     QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
61     \l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
62
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.
66
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.
75
76     \sa QAbstractSocket, QTcpSocket
77
78     \sa {QWebSocket client example}
79 */
80
81 /*!
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
85     it receives back.
86
87     \section1 Description
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.
91     \section1 Code
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.
95
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.
100
101     \snippet echoclient/echoclient.cpp onTextMessageReceived
102     Whenever a message is received, we write it out.
103 */
104
105 /*!
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()
111 */
112 /*!
113   \fn void QWebSocket::disconnected()
114   \brief Emitted when the socket is disconnected.
115   \sa close(), connected()
116 */
117 /*!
118     \fn void QWebSocket::aboutToClose()
119
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).
123
124     \sa close()
125  */
126 /*!
127 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
128
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.
133
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.
137
138 \sa QAuthenticator, QNetworkProxy
139 */
140 /*!
141     \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
142
143     This signal is emitted whenever QWebSocket's state changes.
144     The \a state parameter is the new state.
145
146     \note QAbstractSocket::ConnectedState is emitted after the handshake
147     with the server has succeeded.
148
149     QAbstractSocket::SocketState is not a registered metatype, so for queued
150     connections, you will have to register it with Q_REGISTER_METATYPE() and
151     qRegisterMetaType().
152
153     \sa state()
154 */
155 /*!
156     \fn void QWebSocket::readChannelFinished()
157
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.
160
161     \sa close()
162 */
163 /*!
164     \fn void QWebSocket::bytesWritten(qint64 bytes)
165
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.
168
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()).
172     \sa close()
173 */
174
175 /*!
176     \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
177
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.
180
181     This signal can be used to process large messages frame by frame, instead of waiting for the
182     complete message to arrive.
183
184     \sa binaryFrameReceived()
185 */
186 /*!
187     \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
188
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.
191
192     This signal can be used to process large messages frame by frame, instead of waiting for the
193     complete message to arrive.
194
195     \sa textFrameReceived()
196 */
197 /*!
198     \fn void QWebSocket::textMessageReceived(const QString &message);
199
200     This signal is emitted whenever a text message is received. The \a message contains the
201     received text.
202
203     \sa binaryMessageReceived()
204 */
205 /*!
206     \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
207
208     This signal is emitted whenever a binary message is received. The \a message contains the
209     received bytes.
210
211     \sa textMessageReceived()
212 */
213 /*!
214     \fn void QWebSocket::error(QAbstractSocket::SocketError error);
215
216     This signal is emitted after an error occurred. The \a error
217     parameter describes the type of error that occurred.
218
219     QAbstractSocket::SocketError is not a registered metatype, so for queued
220     connections, you will have to register it with Q_DECLARE_METATYPE() and
221     qRegisterMetaType().
222
223     \sa error(), errorString()
224 */
225 /*!
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()
234     (without arguments).
235
236     \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
237     the peer.
238
239     \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
240     QWebSocket::ignoreSslErrors() will have no effect.
241 */
242 /*!
243     \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
244
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.
248
249     \sa ping()
250   */
251 #include "qwebsocket.h"
252 #include "qwebsocket_p.h"
253
254 #include <QtCore/QUrl>
255 #include <QtNetwork/QTcpSocket>
256 #include <QtCore/QByteArray>
257 #include <QtNetwork/QHostAddress>
258
259 #include <QtCore/QDebug>
260
261 #include <limits>
262
263 QT_BEGIN_NAMESPACE
264
265 /*!
266  * \brief Creates a new QWebSocket with the given \a origin,
267  * the \a version of the protocol to use and \a parent.
268  *
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
275  */
276 QWebSocket::QWebSocket(const QString &origin,
277                        QWebSocketProtocol::Version version,
278                        QObject *parent) :
279     QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
280 {
281     Q_D(QWebSocket);
282     d->init();
283 }
284
285 /*!
286  * \brief Destroys the QWebSocket. Closes the socket if it is still open,
287  * and releases any used resources.
288  */
289 QWebSocket::~QWebSocket()
290 {
291 }
292
293 /*!
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.
297  */
298 void QWebSocket::abort()
299 {
300     Q_D(QWebSocket);
301     d->abort();
302 }
303
304 /*!
305  * Returns the type of error that last occurred
306  * \sa errorString()
307  */
308 QAbstractSocket::SocketError QWebSocket::error() const
309 {
310     Q_D(const QWebSocket);
311     return d->error();
312 }
313
314 //only called by QWebSocketPrivate::upgradeFrom
315 /*!
316   \internal
317  */
318 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
319                        QWebSocketProtocol::Version version, QObject *parent) :
320     QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
321 {
322     Q_D(QWebSocket);
323     d->init();
324 }
325
326 /*!
327  * Returns a human-readable description of the last error that occurred
328  *
329  * \sa error()
330  */
331 QString QWebSocket::errorString() const
332 {
333     Q_D(const QWebSocket);
334     return d->errorString();
335 }
336
337 /*!
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.
346 */
347 bool QWebSocket::flush()
348 {
349     Q_D(QWebSocket);
350     return d->flush();
351 }
352
353 /*!
354     \brief Sends the given \a message over the socket as a text message and
355     returns the number of bytes actually sent.
356
357     \sa sendBinaryMessage()
358  */
359 qint64 QWebSocket::sendTextMessage(const QString &message)
360 {
361     Q_D(QWebSocket);
362     return d->sendTextMessage(message);
363 }
364
365 /*!
366     \brief Sends the given \a data over the socket as a binary message and
367     returns the number of bytes actually sent.
368
369     \sa sendTextMessage()
370  */
371 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
372 {
373     Q_D(QWebSocket);
374     return d->sendBinaryMessage(data);
375 }
376
377 /*!
378     \brief Gracefully closes the socket with the given \a closeCode and \a reason.
379
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
383  */
384 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
385 {
386     Q_D(QWebSocket);
387     d->close(closeCode, reason);
388 }
389
390 /*!
391     \brief Opens a WebSocket connection using the given \a url.
392
393     If the url contains newline characters (\\r\\n), then the error signal will be emitted
394     with QAbstractSocket::ConnectionRefusedError as error type.
395  */
396 void QWebSocket::open(const QUrl &url)
397 {
398     Q_D(QWebSocket);
399     d->open(url, true);
400 }
401
402 /*!
403     \brief Pings the server to indicate that the connection is still alive.
404     Additional \a payload can be sent along the ping message.
405
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.
408
409     \sa pong()
410  */
411 void QWebSocket::ping(const QByteArray &payload)
412 {
413     Q_D(QWebSocket);
414     d->ping(payload);
415 }
416
417 #ifndef QT_NO_SSL
418 /*!
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
426     been emitted.
427
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
434     with great care!
435
436     \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
437 */
438 void QWebSocket::ignoreSslErrors()
439 {
440     Q_D(QWebSocket);
441     d->ignoreSslErrors();
442 }
443
444 /*!
445     \overload
446
447     This method tells QWebSocket to ignore the errors given in \a errors.
448
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:
452
453     \snippet src_websockets_ssl_qwebsocket.cpp 6
454
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.
459
460     \sa sslErrors()
461 */
462 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
463 {
464     Q_D(QWebSocket);
465     d->ignoreSslErrors(errors);
466 }
467
468 /*!
469     Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
470
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()
475  */
476 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
477 {
478     Q_D(QWebSocket);
479     d->setSslConfiguration(sslConfiguration);
480 }
481
482 /*!
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.
487
488     \sa setSslConfiguration()
489  */
490 QSslConfiguration QWebSocket::sslConfiguration() const
491 {
492     Q_D(const QWebSocket);
493     return d->sslConfiguration();
494 }
495
496 #endif  //not QT_NO_SSL
497
498 /*!
499     \brief Returns the version the socket is currently using.
500  */
501 QWebSocketProtocol::Version QWebSocket::version() const
502 {
503     Q_D(const QWebSocket);
504     return d->version();
505 }
506
507 /*!
508     \brief Returns the name of the resource currently accessed.
509  */
510 QString QWebSocket::resourceName() const
511 {
512     Q_D(const QWebSocket);
513     return d->resourceName();
514 }
515
516 /*!
517     \brief Returns the url the socket is connected to or will connect to.
518  */
519 QUrl QWebSocket::requestUrl() const
520 {
521     Q_D(const QWebSocket);
522     return d->requestUrl();
523 }
524
525 /*!
526     \brief Returns the current origin.
527  */
528 QString QWebSocket::origin() const
529 {
530     Q_D(const QWebSocket);
531     return d->origin();
532 }
533
534 /*!
535     \brief Returns the code indicating why the socket was closed.
536     \sa QWebSocketProtocol::CloseCode, closeReason()
537  */
538 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
539 {
540     Q_D(const QWebSocket);
541     return d->closeCode();
542 }
543
544 /*!
545     \brief Returns the reason why the socket was closed.
546     \sa closeCode()
547  */
548 QString QWebSocket::closeReason() const
549 {
550     Q_D(const QWebSocket);
551     return d->closeReason();
552 }
553
554 /*!
555     \brief Returns the current state of the socket.
556  */
557 QAbstractSocket::SocketState QWebSocket::state() const
558 {
559     Q_D(const QWebSocket);
560     return d->state();
561 }
562
563 /*!
564     Returns the local address
565  */
566 QHostAddress QWebSocket::localAddress() const
567 {
568     Q_D(const QWebSocket);
569     return d->localAddress();
570 }
571
572 /*!
573     Returns the local port
574  */
575 quint16 QWebSocket::localPort() const
576 {
577     Q_D(const QWebSocket);
578     return d->localPort();
579 }
580
581 /*!
582     Returns the pause mode of this socket
583  */
584 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
585 {
586     Q_D(const QWebSocket);
587     return d->pauseMode();
588 }
589
590 /*!
591     Returns the peer address
592  */
593 QHostAddress QWebSocket::peerAddress() const
594 {
595     Q_D(const QWebSocket);
596     return d->peerAddress();
597 }
598
599 /*!
600     Returns the peerName
601  */
602 QString QWebSocket::peerName() const
603 {
604     Q_D(const QWebSocket);
605     return d->peerName();
606 }
607
608 /*!
609     Returns the peerport
610  */
611 quint16 QWebSocket::peerPort() const
612 {
613     Q_D(const QWebSocket);
614     return d->peerPort();
615 }
616
617 #ifndef QT_NO_NETWORKPROXY
618 /*!
619     Returns the currently configured proxy
620  */
621 QNetworkProxy QWebSocket::proxy() const
622 {
623     Q_D(const QWebSocket);
624     return d->proxy();
625 }
626
627 /*!
628     Sets the proxy to \a networkProxy
629  */
630 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
631 {
632     Q_D(QWebSocket);
633     d->setProxy(networkProxy);
634 }
635 #endif
636
637 /*!
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.
641  */
642 void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
643 {
644     Q_D(QWebSocket);
645     d->setMaskGenerator(maskGenerator);
646 }
647
648 /*!
649     Returns the mask generator that is currently used by this QWebSocket.
650  */
651 const QMaskGenerator *QWebSocket::maskGenerator() const
652 {
653     Q_D(const QWebSocket);
654     return d->maskGenerator();
655 }
656
657 /*!
658     Returns the size in bytes of the readbuffer that is used by the socket.
659  */
660 qint64 QWebSocket::readBufferSize() const
661 {
662     Q_D(const QWebSocket);
663     return d->readBufferSize();
664 }
665
666 /*!
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.
671
672     \sa pauseMode(), setPauseMode()
673  */
674 void QWebSocket::resume()
675 {
676     Q_D(QWebSocket);
677     d->resume();
678 }
679
680 /*!
681     Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
682     the conditions in which the socket should be paused.
683
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.
689
690     \sa pauseMode(), resume()
691  */
692 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
693 {
694     Q_D(QWebSocket);
695     d->setPauseMode(pauseMode);
696 }
697
698 /*!
699     Sets the size of QWebSocket's internal read buffer to be \a size bytes.
700
701     If the buffer size is limited to a certain size, QWebSocket won't buffer more than
702     this size of data.
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.
708
709     \sa readBufferSize()
710 */
711 void QWebSocket::setReadBufferSize(qint64 size)
712 {
713     Q_D(QWebSocket);
714     d->setReadBufferSize(size);
715 }
716
717 /*!
718     Returns \c true if the socket is ready for reading and writing; otherwise
719     returns \c false.
720  */
721 bool QWebSocket::isValid() const
722 {
723     Q_D(const QWebSocket);
724     return d->isValid();
725 }
726
727 QT_END_NAMESPACE