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