6e60230d2743233cb0a70abc3428b23d1e16febe
[contrib/qtwebsockets.git] / src / websockets / qwebsocket.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
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 RFC 6455.
61
62     \sa QAbstractSocket, QTcpSocket
63
64     \sa {QWebSocket client example}
65 */
66
67 /*!
68     \page echoclient.html example
69     \title QWebSocket client example
70     \brief A sample websocket client that sends a message and displays the message that
71     it receives back.
72
73     \section1 Description
74     The EchoClient example implements a web socket client that sends a message to a websocket server
75     and dumps the answer that it gets back.
76     This example should ideally be used with the EchoServer example.
77     \section1 Code
78     We start by connecting to the `connected()` signal.
79     \snippet echoclient/echoclient.cpp constructor
80     After the connection, we open the socket to the given \a url.
81
82     \snippet echoclient/echoclient.cpp onConnected
83     When the client is connected successfully, we connect to the `onTextMessageReceived()` signal,
84     and send out "Hello, world!".
85     If connected with the EchoServer, we will receive the same message back.
86
87     \snippet echoclient/echoclient.cpp onTextMessageReceived
88     Whenever a message is received, we write it out.
89 */
90
91 /*!
92   \fn void QWebSocket::connected()
93   \brief Emitted when a connection is successfully established.
94   A connection is successfully established when the socket is connected
95   and the handshake was successful.
96   \sa open(), disconnected()
97 */
98 /*!
99   \fn void QWebSocket::disconnected()
100   \brief Emitted when the socket is disconnected.
101   \sa close(), connected()
102 */
103 /*!
104     \fn void QWebSocket::aboutToClose()
105
106     This signal is emitted when the socket is about to close.
107     Connect this signal if you have operations that need to be performed before the socket closes
108     (e.g., if you have data in a separate buffer that needs to be written to the device).
109
110     \sa close()
111  */
112 /*!
113 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
114
115 This signal can be emitted when a \a proxy that requires
116 authentication is used. The \a authenticator object can then be
117 filled in with the required details to allow authentication and
118 continue the connection.
119
120 \note It is not possible to use a QueuedConnection to connect to
121 this signal, as the connection will fail if the authenticator has
122 not been filled in with new information when the signal returns.
123
124 \sa QAuthenticator, QNetworkProxy
125 */
126 /*!
127     \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
128
129     This signal is emitted whenever QWebSocket's state changes.
130     The \a state parameter is the new state.
131
132     \note QAbstractSocket::ConnectedState is emitted after the handshake has
133     with the server has succeeded.
134
135     QAbstractSocket::SocketState is not a registered metatype, so for queued
136     connections, you will have to register it with Q_REGISTER_METATYPE() and
137     qRegisterMetaType().
138
139     \sa state()
140 */
141 /*!
142     \fn void QWebSocket::readChannelFinished()
143
144     This signal is emitted when the input (reading) stream is closed in this device.
145     It is emitted as soon as the closing is detected.
146
147     \sa close()
148 */
149 /*!
150     \fn void QWebSocket::bytesWritten(qint64 bytes)
151
152     This signal is emitted every time a payload of data has been written to the socket.
153     The \a bytes argument is set to the number of bytes that were written in this payload.
154
155     \note This signal has the same meaning both for secure and non-secure websockets.
156     As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively
157     written (see QSslSocket:encryptedBytesWritten()).
158     \sa close()
159 */
160
161 /*!
162     \fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
163
164     This signal is emitted whenever a text frame is received. The \a frame contains the data and
165     \a isLastFrame indicates whether this is the last frame of the complete message.
166
167     This signal can be used to process large messages frame by frame, instead of waiting for the
168     complete message to arrive.
169
170     \sa binaryFrameReceived()
171 */
172 /*!
173     \fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
174
175     This signal is emitted whenever a binary frame is received. The \a frame contains the data and
176     \a isLastFrame indicates whether this is the last frame of the complete message.
177
178     This signal can be used to process large messages frame by frame, instead of waiting for the
179     complete message to arrive.
180
181     \sa textFrameReceived()
182 */
183 /*!
184     \fn void QWebSocket::textMessageReceived(const QString &message);
185
186     This signal is emitted whenever a text message is received. The \a message contains the
187     received text.
188
189     \sa binaryMessageReceived()
190 */
191 /*!
192     \fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
193
194     This signal is emitted whenever a binary message is received. The \a message contains the
195     received bytes.
196
197     \sa textMessageReceived()
198 */
199 /*!
200     \fn void QWebSocket::error(QAbstractSocket::SocketError error);
201
202     This signal is emitted after an error occurred. The \a error
203     parameter describes the type of error that occurred.
204
205     QAbstractSocket::SocketError is not a registered metatype, so for queued
206     connections, you will have to register it with Q_DECLARE_METATYPE() and
207     qRegisterMetaType().
208
209     \sa error(), errorString()
210 */
211 /*!
212     \fn void QWebSocket::sslErrors(const QList<QSslError> &errors)
213     QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have
214     occurred while establishing the identity of the peer.
215     The errors are usually an indication that QWebSocket is unable to securely identify the peer.
216     Unless any action is taken, the connection will be dropped after this signal has been emitted.
217     If you want to continue connecting despite the errors that have occurred, you must call
218     QWebSocket::ignoreSslErrors() from inside a slot connected to this signal.
219     If you need to access the error list at a later point, you can call sslErrors()
220     (without arguments).
221
222     \a errors contains one or more errors that prevent QWebSocket from verifying the identity of
223     the peer.
224
225     \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
226     QWebSocket::ignoreSslErrors() will have no effect.
227 */
228 /*!
229     \fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
230
231     Emitted when a pong message is received in reply to a previous ping.
232     \a elapsedTime contains the roundtrip time in milliseconds and \a payload contains an optional
233     payload that was sent with the ping.
234
235     \sa ping()
236   */
237 #include "qwebsocket.h"
238 #include "qwebsocket_p.h"
239
240 #include <QtCore/QUrl>
241 #include <QtNetwork/QTcpSocket>
242 #include <QtCore/QByteArray>
243 #include <QtNetwork/QHostAddress>
244
245 #include <QtCore/QDebug>
246
247 #include <limits>
248
249 QT_BEGIN_NAMESPACE
250
251 /*!
252  * \brief Creates a new QWebSocket with the given \a origin,
253  * the \a version of the protocol to use and \a parent.
254  *
255  * The \a origin of the client is as specified \l {http://tools.ietf.org/html/rfc6454}{RFC 6454}.
256  * (The \a origin is not required for non-web browser clients
257  * (see \l {http://tools.ietf.org/html/rfc6455}{RFC 6455})).
258  * \note Currently only V13 (\l {http://tools.ietf.org/html/rfc6455} {RFC 6455}) is supported
259  */
260 QWebSocket::QWebSocket(const QString &origin,
261                        QWebSocketProtocol::Version version,
262                        QObject *parent) :
263     QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
264 {
265     Q_D(QWebSocket);
266     d->init();
267 }
268
269 /*!
270  * \brief Destroys the QWebSocket. Closes the socket if it is still open,
271  * and releases any used resources.
272  */
273 QWebSocket::~QWebSocket()
274 {
275 }
276
277 /*!
278  * \brief Aborts the current socket and resets the socket.
279  * Unlike close(), this function immediately closes the socket,
280  * discarding any pending data in the write buffer.
281  */
282 void QWebSocket::abort()
283 {
284     Q_D(QWebSocket);
285     d->abort();
286 }
287
288 /*!
289  * Returns the type of error that last occurred
290  * \sa errorString()
291  */
292 QAbstractSocket::SocketError QWebSocket::error() const
293 {
294     Q_D(const QWebSocket);
295     return d->error();
296 }
297
298 //only called by QWebSocketPrivate::upgradeFrom
299 /*!
300   \internal
301  */
302 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
303                        QWebSocketProtocol::Version version, QObject *parent) :
304     QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
305 {
306     Q_D(QWebSocket);
307     d->init();
308 }
309
310 /*!
311  * Returns a human-readable description of the last error that occurred
312  *
313  * \sa error()
314  */
315 QString QWebSocket::errorString() const
316 {
317     Q_D(const QWebSocket);
318     return d->errorString();
319 }
320
321 /*!
322     This function writes as much as possible from the internal write buffer
323     to the underlying network socket, without blocking.
324     If any data was written, this function returns true; otherwise false is returned.
325     Call this function if you need QWebSocket to start sending buffered data immediately.
326     The number of bytes successfully written depends on the operating system.
327     In most cases, you do not need to call this function,
328     because QWebSocket will start sending data automatically
329     once control goes back to the event loop.
330 */
331 bool QWebSocket::flush()
332 {
333     Q_D(QWebSocket);
334     return d->flush();
335 }
336
337 /*!
338     \brief Sends the given \a message over the socket as a text message and
339     returns the number of bytes actually sent.
340
341     \sa sendBinaryMessage()
342  */
343 qint64 QWebSocket::sendTextMessage(const QString &message)
344 {
345     Q_D(QWebSocket);
346     return d->sendTextMessage(message);
347 }
348
349 /*!
350     \brief Sends the given \a data over the socket as a binary message and
351     returns the number of bytes actually sent.
352
353     \sa sendTextMessage()
354  */
355 qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
356 {
357     Q_D(QWebSocket);
358     return d->sendBinaryMessage(data);
359 }
360
361 /*!
362     \brief Gracefully closes the socket with the given \a closeCode and \a reason.
363
364     Any data in the write buffer is flushed before the socket is closed.
365     The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
366     \a reason describes the reason of the closure more in detail
367  */
368 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
369 {
370     Q_D(QWebSocket);
371     d->close(closeCode, reason);
372 }
373
374 /*!
375     \brief Opens a websocket connection using the given \a url.
376     If \a mask is true, all frames will be masked; this is only necessary for client side sockets;
377     servers should never mask.
378     \note A client socket must *always* mask its frames; servers may *never* mask its frames.
379  */
380 void QWebSocket::open(const QUrl &url, bool mask)
381 {
382     Q_D(QWebSocket);
383     d->open(url, mask);
384 }
385
386 /*!
387     \brief Pings the server to indicate that the connection is still alive.
388     Additional \a payload can be sent along the ping message.
389
390     The size of the \a payload cannot be bigger than 125.
391     If it is larger, the \a payload is clipped to 125 bytes.
392
393     \sa pong()
394  */
395 void QWebSocket::ping(const QByteArray &payload)
396 {
397     Q_D(QWebSocket);
398     d->ping(payload);
399 }
400
401 #ifndef QT_NO_SSL
402 /*!
403     This slot tells QWebSocket to ignore errors during QWebSocket's
404     handshake phase and continue connecting. If you want to continue
405     with the connection even if errors occur during the handshake
406     phase, then you must call this slot, either from a slot connected
407     to sslErrors(), or before the handshake phase. If you don't call
408     this slot, either in response to errors or before the handshake,
409     the connection will be dropped after the sslErrors() signal has
410     been emitted.
411
412     \warning Be sure to always let the user inspect the errors
413     reported by the sslErrors() signal, and only call this method
414     upon confirmation from the user that proceeding is ok.
415     If there are unexpected errors, the connection should be aborted.
416     Calling this method without inspecting the actual errors will
417     most likely pose a security risk for your application. Use it
418     with great care!
419
420     \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
421 */
422 void QWebSocket::ignoreSslErrors()
423 {
424     Q_D(QWebSocket);
425     d->ignoreSslErrors();
426 }
427
428 /*!
429     \overload
430
431     This method tells QWebSocket to ignore the errors given in \a errors.
432
433     Note that you can set the expected certificate in the SSL error:
434     If, for instance, you want to connect to a server that uses
435     a self-signed certificate, consider the following snippet:
436
437     \snippet src_websockets_ssl_qwebsocket.cpp 6
438
439     Multiple calls to this function will replace the list of errors that
440     were passed in previous calls.
441     You can clear the list of errors you want to ignore by calling this
442     function with an empty list.
443
444     \sa sslErrors()
445 */
446 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
447 {
448     Q_D(QWebSocket);
449     d->ignoreSslErrors(errors);
450 }
451
452 /*!
453     Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
454
455     This function sets the local certificate, the ciphers, the private key and
456     the CA certificates to those stored in \a sslConfiguration.
457     It is not possible to set the SSL-state related fields.
458     \sa sslConfiguration()
459  */
460 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
461 {
462     Q_D(QWebSocket);
463     d->setSslConfiguration(sslConfiguration);
464 }
465
466 /*!
467     Returns the socket's SSL configuration state.
468     The default SSL configuration of a socket is to use the default ciphers,
469     default CA certificates, no local private key or certificate.
470     The SSL configuration also contains fields that can change with time without notice.
471
472     \sa setSslConfiguration()
473  */
474 QSslConfiguration QWebSocket::sslConfiguration() const
475 {
476     Q_D(const QWebSocket);
477     return d->sslConfiguration();
478 }
479
480 #endif  //not QT_NO_SSL
481
482 /*!
483     \brief Returns the version the socket is currently using
484  */
485 QWebSocketProtocol::Version QWebSocket::version() const
486 {
487     Q_D(const QWebSocket);
488     return d->version();
489 }
490
491 /*!
492     \brief Returns the name of the resource currently accessed.
493  */
494 QString QWebSocket::resourceName() const
495 {
496     Q_D(const QWebSocket);
497     return d->resourceName();
498 }
499
500 /*!
501     \brief Returns the url the socket is connected to or will connect to.
502  */
503 QUrl QWebSocket::requestUrl() const
504 {
505     Q_D(const QWebSocket);
506     return d->requestUrl();
507 }
508
509 /*!
510     \brief Returns the current origin
511  */
512 QString QWebSocket::origin() const
513 {
514     Q_D(const QWebSocket);
515     return d->origin();
516 }
517
518 /*!
519     \brief Returns the code indicating why the socket was closed.
520     \sa QWebSocketProtocol::CloseCode, closeReason()
521  */
522 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
523 {
524     Q_D(const QWebSocket);
525     return d->closeCode();
526 }
527
528 /*!
529     \brief Returns the reason why the socket was closed.
530     \sa closeCode()
531  */
532 QString QWebSocket::closeReason() const
533 {
534     Q_D(const QWebSocket);
535     return d->closeReason();
536 }
537
538 /*!
539     \brief Returns the current state of the socket
540  */
541 QAbstractSocket::SocketState QWebSocket::state() const
542 {
543     Q_D(const QWebSocket);
544     return d->state();
545 }
546
547 /*!
548     Returns the local address
549  */
550 QHostAddress QWebSocket::localAddress() const
551 {
552     Q_D(const QWebSocket);
553     return d->localAddress();
554 }
555
556 /*!
557     Returns the local port
558  */
559 quint16 QWebSocket::localPort() const
560 {
561     Q_D(const QWebSocket);
562     return d->localPort();
563 }
564
565 /*!
566     Returns the pause mode of this socket
567  */
568 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
569 {
570     Q_D(const QWebSocket);
571     return d->pauseMode();
572 }
573
574 /*!
575     Returns the peer address
576  */
577 QHostAddress QWebSocket::peerAddress() const
578 {
579     Q_D(const QWebSocket);
580     return d->peerAddress();
581 }
582
583 /*!
584     Returns the peerName
585  */
586 QString QWebSocket::peerName() const
587 {
588     Q_D(const QWebSocket);
589     return d->peerName();
590 }
591
592 /*!
593     Returns the peerport
594  */
595 quint16 QWebSocket::peerPort() const
596 {
597     Q_D(const QWebSocket);
598     return d->peerPort();
599 }
600
601 #ifndef QT_NO_NETWORKPROXY
602 /*!
603     Returns the currently configured proxy
604  */
605 QNetworkProxy QWebSocket::proxy() const
606 {
607     Q_D(const QWebSocket);
608     return d->proxy();
609 }
610
611 /*!
612     Sets the proxy to \a networkProxy
613  */
614 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
615 {
616     Q_D(QWebSocket);
617     d->setProxy(networkProxy);
618 }
619 #endif
620
621 /*!
622     Returns the size in bytes of the readbuffer that is used by the socket.
623  */
624 qint64 QWebSocket::readBufferSize() const
625 {
626     Q_D(const QWebSocket);
627     return d->readBufferSize();
628 }
629
630 /*!
631     Continues data transfer on the socket. This method should only be used after the socket
632     has been set to pause upon notifications and a notification has been received.
633     The only notification currently supported is sslErrors().
634     Calling this method if the socket is not paused results in undefined behavior.
635
636     \sa pauseMode(), setPauseMode()
637  */
638 void QWebSocket::resume()
639 {
640     Q_D(QWebSocket);
641     d->resume();
642 }
643
644 /*!
645     Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
646     the conditions in which the socket should be paused.
647
648     The only notification currently supported is sslErrors().
649     If set to PauseOnSslErrors, data transfer on the socket will be paused
650     and needs to be enabled explicitly again by calling resume().
651     By default, this option is set to PauseNever. This option must be called
652     before connecting to the server, otherwise it will result in undefined behavior.
653
654     \sa pauseMode(), resume()
655  */
656 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
657 {
658     Q_D(QWebSocket);
659     d->setPauseMode(pauseMode);
660 }
661
662 /*!
663     Sets the size of QWebSocket's internal read buffer to be \a size bytes.
664
665     If the buffer size is limited to a certain size, QWebSocket won't buffer more than
666     this size of data.
667     Exceptionally, a buffer size of 0 means that the read buffer is unlimited and
668     all incoming data is buffered. This is the default.
669     This option is useful if you only read the data at certain points in time
670     (e.g., in a real-time streaming application) or if you want to protect your socket against
671     receiving too much data, which may eventually cause your application to run out of memory.
672
673     \sa readBufferSize()
674 */
675 void QWebSocket::setReadBufferSize(qint64 size)
676 {
677     Q_D(QWebSocket);
678     d->setReadBufferSize(size);
679 }
680
681 /*!
682     Returns \c true if the socket is ready for reading and writing; otherwise
683     returns \c false.
684  */
685 bool QWebSocket::isValid() const
686 {
687     Q_D(const QWebSocket);
688     return d->isValid();
689 }
690
691 QT_END_NAMESPACE