source: trunk/src/network/ssl/qsslsocket.cpp@ 64

Last change on this file since 64 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 65.9 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the QtNetwork module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42
43//#define QSSLSOCKET_DEBUG
44
45/*!
46 \class QSslSocket
47 \brief The QSslSocket class provides an SSL encrypted socket for both
48 clients and servers.
49 \since 4.3
50
51 \reentrant
52 \ingroup io
53 \ingroup ssl
54 \inmodule QtNetwork
55
56 QSslSocket establishes a secure, encrypted TCP connection you can
57 use for transmitting encrypted data. It can operate in both client
58 and server mode, and it supports modern SSL protocols, including
59 SSLv3 and TLSv1. By default, QSslSocket uses SSLv3, but you can
60 change the SSL protocol by calling setProtocol() as long as you do
61 it before the handshake has started.
62
63 SSL encryption operates on top of the existing TCP stream after
64 the socket enters the ConnectedState. There are two simple ways to
65 establish a secure connection using QSslSocket: With an immediate
66 SSL handshake, or with a delayed SSL handshake occurring after the
67 connection has been established in unencrypted mode.
68
69 The most common way to use QSslSocket is to construct an object
70 and start a secure connection by calling connectToHostEncrypted().
71 This method starts an immediate SSL handshake once the connection
72 has been established.
73
74 \snippet doc/src/snippets/code/src_network_ssl_qsslsocket.cpp 0
75
76 As with a plain QTcpSocket, QSslSocket enters the HostLookupState,
77 ConnectingState, and finally the ConnectedState, if the connection
78 is successful. The handshake then starts automatically, and if it
79 succeeds, the encrypted() signal is emitted to indicate the socket
80 has entered the encrypted state and is ready for use.
81
82 Note that data can be written to the socket immediately after the
83 return from connectToHostEncrypted() (i.e., before the encrypted()
84 signal is emitted). The data is queued in QSslSocket until after
85 the encrypted() signal is emitted.
86
87 An example of using the delayed SSL handshake to secure an
88 existing connection is the case where an SSL server secures an
89 incoming connection. Suppose you create an SSL server class as a
90 subclass of QTcpServer. You would override
91 QTcpServer::incomingConnection() with something like the example
92 below, which first constructs an instance of QSslSocket and then
93 calls setSocketDescriptor() to set the new socket's descriptor to
94 the existing one passed in. It then initiates the SSL handshake
95 by calling startServerEncryption().
96
97 \snippet doc/src/snippets/code/src_network_ssl_qsslsocket.cpp 1
98
99 If an error occurs, QSslSocket emits the sslErrors() signal. In this
100 case, if no action is taken to ignore the error(s), the connection
101 is dropped. To continue, despite the occurrence of an error, you
102 can call ignoreSslErrors(), either from within this slot after the
103 error occurs, or any time after construction of the QSslSocket and
104 before the connection is attempted. This will allow QSslSocket to
105 ignore the errors it encounters when establishing the identity of
106 the peer. Ignoring errors during an SSL handshake should be used
107 with caution, since a fundamental characteristic of secure
108 connections is that they should be established with a successful
109 handshake.
110
111 Once encrypted, you use QSslSocket as a regular QTcpSocket. When
112 readyRead() is emitted, you can call read(), canReadLine() and
113 readLine(), or getChar() to read decrypted data from QSslSocket's
114 internal buffer, and you can call write() or putChar() to write
115 data back to the peer. QSslSocket will automatically encrypt the
116 written data for you, and emit bytesWritten() once the data has
117 been written to the peer.
118
119 As a convenience, QSslSocket supports QTcpSocket's blocking
120 functions waitForConnected(), waitForReadyRead(),
121 waitForBytesWritten(), and waitForDisconnected(). It also provides
122 waitForEncrypted(), which will block the calling thread until an
123 encrypted connection has been established.
124
125 \snippet doc/src/snippets/code/src_network_ssl_qsslsocket.cpp 2
126
127 QSslSocket provides an extensive, easy-to-use API for handling
128 cryptographic ciphers, private keys, and local, peer, and
129 Certification Authority (CA) certificates. It also provides an API
130 for handling errors that occur during the handshake phase.
131
132 The following features can also be customized:
133
134 \list
135 \o The socket's cryptographic cipher suite can be customized before
136 the handshake phase with setCiphers() and setDefaultCiphers().
137 \o The socket's local certificate and private key can be customized
138 before the handshake phase with setLocalCertificate() and
139 setPrivateKey().
140 \o The CA certificate database can be extended and customized with
141 addCaCertificate(), addCaCertificates(), setCaCertificates(),
142 addDefaultCaCertificate(), addDefaultCaCertificates(), and
143 setDefaultCaCertificates().
144 \endlist
145
146 For more information about ciphers and certificates, refer to QSslCipher and
147 QSslCertificate.
148
149 This product includes software developed by the OpenSSL Project
150 for use in the OpenSSL Toolkit (\l{http://www.openssl.org/}).
151
152 \sa QSslCertificate, QSslCipher, QSslError
153*/
154
155/*!
156 \enum QSslSocket::SslMode
157
158 Describes the connection modes available for QSslSocket.
159
160 \value UnencryptedMode The socket is unencrypted. Its
161 behavior is identical to QTcpSocket.
162
163 \value SslClientMode The socket is a client-side SSL socket.
164 It is either alreayd encrypted, or it is in the SSL handshake
165 phase (see QSslSocket::isEncrypted()).
166
167 \value SslServerMode The socket is a server-side SSL socket.
168 It is either already encrypted, or it is in the SSL handshake
169 phase (see QSslSocket::isEncrypted()).
170*/
171
172/*!
173 \enum QSslSocket::PeerVerifyMode
174 \since 4.4
175
176 Describes the peer verification modes for QSslSocket. The default mode is
177 AutoVerifyPeer, which selects an appropriate mode depending on the
178 socket's QSocket::SslMode.
179
180 \value VerifyNone QSslSocket will not request a certificate from the
181 peer. You can set this mode if you are not interested in the identity of
182 the other side of the connection. The connection will still be encrypted,
183 and your socket will still send its local certificate to the peer if it's
184 requested.
185
186 \value QueryPeer QSslSocket will request a certificate from the peer, but
187 does not require this certificate to be valid. This is useful when you
188 want to display peer certificate details to the user without affecting the
189 actual SSL handshake. This mode is the default for servers.
190
191 \value VerifyPeer QSslSocket will request a certificate from the peer
192 during the SSL handshake phase, and requires that this certificate is
193 valid. On failure, QSslSocket will emit the QSslSocket::sslErrors()
194 signal. This mode is the default for clients.
195
196 \value AutoVerifyPeer QSslSocket will automaticaly use QueryPeer for
197 server sockets and VerifyPeer for client sockets.
198
199 \sa QSslSocket::peerVerifyMode()
200*/
201
202/*!
203 \fn QSslSocket::encrypted()
204
205 This signal is emitted when QSslSocket enters encrypted mode. After this
206 signal has been emitted, QSslSocket::isEncrypted() will return true, and
207 all further transmissions on the socket will be encrypted.
208
209 \sa QSslSocket::connectToHostEncrypted(), QSslSocket::isEncrypted()
210*/
211
212/*!
213 \fn QSslSocket::modeChanged(QSslSocket::SslMode mode)
214
215 This signal is emitted when QSslSocket changes from \l
216 QSslSocket::UnencryptedMode to either \l QSslSocket::SslClientMode or \l
217 QSslSocket::SslServerMode. \a mode is the new mode.
218
219 \sa QSslSocket::mode()
220*/
221
222/*!
223 \fn QSslSocket::encryptedBytesWritten(qint64 written)
224 \since 4.4
225
226 This signal is emitted when QSslSocket writes its encrypted data to the
227 network. The \a written parameter contains the number of bytes that were
228 successfully written.
229
230 \sa QIODevice::bytesWritten()
231*/
232
233/*!
234 \fn void QSslSocket::peerVerifyError(const QSslError &error)
235 \since 4.4
236
237 QSslSocket can emit this signal several times during the SSL handshake,
238 before encryption has been established, to indicate that an error has
239 occurred while establishing the identity of the peer. The \a error is
240 usually an indication that QSslSocket is unable to securely identify the
241 peer.
242
243 This signal provides you with an early indication when something's wrong.
244 By connecting to this signal, you can manually choose to tear down the
245 connection from inside the connected slot before the handshake has
246 completed. If no action is taken, QSslSocket will proceed to emitting
247 QSslSocket::sslErrors().
248
249 \sa sslErrors()
250*/
251
252/*!
253 \fn void QSslSocket::sslErrors(const QList<QSslError> &errors);
254
255 QSslSocket emits this signal after the SSL handshake to indicate that one
256 or more errors have occurred while establishing the identity of the
257 peer. The errors are usually an indication that QSslSocket is unable to
258 securely identify the peer. Unless any action is taken, the connection
259 will be dropped after this signal has been emitted.
260
261 If you want to continue connecting despite the errors that have occurred,
262 you must call QSslSocket::ignoreSslErrors() from inside a slot connected to
263 this signal. If you need to access the error list at a later point, you
264 can call sslErrors() (without arguments).
265
266 \a errors contains one or more errors that prevent QSslSocket from
267 verifying the identity of the peer.
268
269 Note: You cannot use Qt::QueuedConnection when connecting to this signal,
270 or calling QSslSocket::ignoreSslErrors() will have no effect.
271
272 \sa peerVerifyError()
273*/
274
275#include "qsslcipher.h"
276#include "qsslsocket.h"
277#include "qsslsocket_openssl_p.h"
278#include "qsslconfiguration_p.h"
279
280#include <QtCore/qdebug.h>
281#include <QtCore/qdir.h>
282#include <QtCore/qdatetime.h>
283#include <QtCore/qmutex.h>
284#include <QtNetwork/qhostaddress.h>
285#include <QtNetwork/qhostinfo.h>
286
287QT_BEGIN_NAMESPACE
288
289/*
290 Returns the difference between msecs and elapsed. If msecs is -1,
291 however, -1 is returned.
292*/
293static int qt_timeout_value(int msecs, int elapsed)
294{
295 if (msecs == -1)
296 return -1;
297
298 int timeout = msecs - elapsed;
299 return timeout < 0 ? 0 : timeout;
300}
301
302class QSslSocketGlobalData
303{
304public:
305 QSslSocketGlobalData() : config(new QSslConfigurationPrivate) {}
306
307 QMutex mutex;
308 QList<QSslCipher> supportedCiphers;
309 QExplicitlySharedDataPointer<QSslConfigurationPrivate> config;
310};
311Q_GLOBAL_STATIC(QSslSocketGlobalData, globalData)
312
313/*!
314 Constructs a QSslSocket object. \a parent is passed to QObject's
315 constructor. The new socket's \l {QSslCipher} {cipher} suite is
316 set to the one returned by the static method defaultCiphers().
317*/
318QSslSocket::QSslSocket(QObject *parent)
319 : QTcpSocket(*new QSslSocketBackendPrivate, parent)
320{
321 Q_D(QSslSocket);
322#ifdef QSSLSOCKET_DEBUG
323 qDebug() << "QSslSocket::QSslSocket(" << parent << "), this =" << (void *)this;
324#endif
325 d->q_ptr = this;
326 d->init();
327}
328
329/*!
330 Destroys the QSslSocket.
331*/
332QSslSocket::~QSslSocket()
333{
334 Q_D(QSslSocket);
335#ifdef QSSLSOCKET_DEBUG
336 qDebug() << "QSslSocket::~QSslSocket(), this =" << (void *)this;
337#endif
338 delete d->plainSocket;
339 d->plainSocket = 0;
340}
341
342/*!
343 Starts an encrypted connection to the device \a hostName on \a
344 port, using \a mode as the \l OpenMode. This is equivalent to
345 calling connectToHost() to establish the connection, followed by a
346 call to startClientEncryption().
347
348 QSslSocket first enters the HostLookupState. Then, after entering
349 either the event loop or one of the waitFor...() functions, it
350 enters the ConnectingState, emits connected(), and then initiates
351 the SSL client handshake. At each state change, QSslSocket emits
352 signal stateChanged().
353
354 After initiating the SSL client handshake, if the identity of the
355 peer can't be established, signal sslErrors() is emitted. If you
356 want to ignore the errors and continue connecting, you must call
357 ignoreSslErrors(), either from inside a slot function connected to
358 the sslErrors() signal, or prior to entering encrypted mode. If
359 ignoreSslErrors is not called, the connection is dropped, signal
360 disconnected() is emitted, and QSslSocket returns to the
361 UnconnectedState.
362
363 If the SSL handshake is successful, QSslSocket emits encrypted().
364
365 \snippet doc/src/snippets/code/src_network_ssl_qsslsocket.cpp 3
366
367 \bold{Note:} The example above shows that text can be written to
368 the socket immediately after requesting the encrypted connection,
369 before the encrypted() signal has been emitted. In such cases, the
370 text is queued in the object and written to the socket \e after
371 the connection is established and the encrypted() signal has been
372 emitted.
373
374 The default for \a mode is \l ReadWrite.
375
376 If you want to create a QSslSocket on the server side of a connection, you
377 should instead call startServerEncryption() upon receiving the incoming
378 connection through QTcpServer.
379
380 \sa connectToHost(), startClientEncryption(), waitForConnected(), waitForEncrypted()
381*/
382void QSslSocket::connectToHostEncrypted(const QString &hostName, quint16 port, OpenMode mode)
383{
384 Q_D(QSslSocket);
385 if (d->state == ConnectedState || d->state == ConnectingState) {
386 qWarning("QSslSocket::connectToHostEncrypted() called when already connecting/connected");
387 return;
388 }
389
390 d->init();
391 d->autoStartHandshake = true;
392 d->initialized = true;
393
394 // Note: When connecting to localhost, some platforms (e.g., HP-UX and some BSDs)
395 // establish the connection immediately (i.e., first attempt).
396 connectToHost(hostName, port, mode);
397}
398
399/*!
400 Initializes QSslSocket with the native socket descriptor \a
401 socketDescriptor. Returns true if \a socketDescriptor is accepted
402 as a valid socket descriptor; otherwise returns false.
403 The socket is opened in the mode specified by \a openMode, and
404 enters the socket state specified by \a state.
405
406 \bold{Note:} It is not possible to initialize two sockets with the same
407 native socket descriptor.
408
409 \sa socketDescriptor()
410*/
411bool QSslSocket::setSocketDescriptor(int socketDescriptor, SocketState state, OpenMode openMode)
412{
413 Q_D(QSslSocket);
414#ifdef QSSLSOCKET_DEBUG
415 qDebug() << "QSslSocket::setSocketDescriptor(" << socketDescriptor << ","
416 << state << "," << openMode << ")";
417#endif
418 if (!d->plainSocket)
419 d->createPlainSocket(openMode);
420 bool retVal = d->plainSocket->setSocketDescriptor(socketDescriptor, state, openMode);
421 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
422 setSocketError(d->plainSocket->error());
423 setSocketState(state);
424 setOpenMode(openMode);
425 setLocalPort(d->plainSocket->localPort());
426 setLocalAddress(d->plainSocket->localAddress());
427 setPeerPort(d->plainSocket->peerPort());
428 setPeerAddress(d->plainSocket->peerAddress());
429 setPeerName(d->plainSocket->peerName());
430 return retVal;
431}
432
433/*!
434 Returns the current mode for the socket; either UnencryptedMode, where
435 QSslSocket behaves identially to QTcpSocket, or one of SslClientMode or
436 SslServerMode, where the client is either negotiating or in encrypted
437 mode.
438
439 When the mode changes, QSslSocket emits modeChanged()
440
441 \sa SslMode
442*/
443QSslSocket::SslMode QSslSocket::mode() const
444{
445 Q_D(const QSslSocket);
446 return d->mode;
447}
448
449/*!
450 Returns true if the socket is encrypted; otherwise, false is returned.
451
452 An encrypted socket encrypts all data that is written by calling write()
453 or putChar() before the data is written to the network, and descrypts all
454 incoming data as the data is received from the network, before you call
455 read(), readLine() or getChar().
456
457 QSslSocket emits encrypted() when it enters encrypted mode.
458
459 You can call sessionCipher() to find which cryptographic cipher is used to
460 encrypt and decrypt your data.
461
462 \sa mode()
463*/
464bool QSslSocket::isEncrypted() const
465{
466 Q_D(const QSslSocket);
467 return d->connectionEncrypted;
468}
469
470/*!
471 Returns the socket's SSL protocol. By default, \l QSsl::SslV3 is used.
472
473 \sa setProtocol()
474*/
475QSsl::SslProtocol QSslSocket::protocol() const
476{
477 Q_D(const QSslSocket);
478 return d->configuration.protocol;
479}
480
481/*!
482 Sets the socket's SSL protocol to \a protocol. This will affect the next
483 initiated handshake; calling this function on an already-encrypted socket
484 will not affect the socket's protocol.
485*/
486void QSslSocket::setProtocol(QSsl::SslProtocol protocol)
487{
488 Q_D(QSslSocket);
489 d->configuration.protocol = protocol;
490}
491
492/*!
493 \since 4.4
494
495 Returns the socket's verify mode. This mode mode decides whether
496 QSslSocket should request a certificate from the peer (i.e., the client
497 requests a certificate from the server, or a server requesting a
498 certificate from the client), and whether it should require that this
499 certificate is valid.
500
501 The default mode is AutoVerifyPeer, which tells QSslSocket to use
502 VerifyPeer for clients, QueryPeer for clients.
503
504 \sa setPeerVerifyMode(), peerVerifyDepth(), mode()
505*/
506QSslSocket::PeerVerifyMode QSslSocket::peerVerifyMode() const
507{
508 Q_D(const QSslSocket);
509 return d->configuration.peerVerifyMode;
510}
511
512/*!
513 \since 4.4
514
515 Sets the socket's verify mode to \a mode. This mode decides whether
516 QSslSocket should request a certificate from the peer (i.e., the client
517 requests a certificate from the server, or a server requesting a
518 certificate from the client), and whether it should require that this
519 certificate is valid.
520
521 The default mode is AutoVerifyPeer, which tells QSslSocket to use
522 VerifyPeer for clients, QueryPeer for clients.
523
524 Setting this mode after encryption has started has no effect on the
525 current connection.
526
527 \sa peerVerifyMode(), setPeerVerifyDepth(), mode()
528*/
529void QSslSocket::setPeerVerifyMode(QSslSocket::PeerVerifyMode mode)
530{
531 Q_D(QSslSocket);
532 d->configuration.peerVerifyMode = mode;
533}
534
535/*!
536 \since 4.4
537
538 Returns the maximum number of certificates in the peer's certificate chain
539 to be checked during the SSL handshake phase, or 0 (the default) if no
540 maximum depth has been set, indicating that the whole certificate chain
541 should be checked.
542
543 The certificates are checked in issuing order, starting with the peer's
544 own certificate, then its issuer's certificate, and so on.
545
546 \sa setPeerVerifyDepth(), peerVerifyMode()
547*/
548int QSslSocket::peerVerifyDepth() const
549{
550 Q_D(const QSslSocket);
551 return d->configuration.peerVerifyDepth;
552}
553
554/*!
555 \since 4.4
556
557 Sets the maximum number of certificates in the peer's certificate chain to
558 be checked during the SSL handshake phase, to \a depth. Setting a depth of
559 0 means that no maximum depth is set, indicating that the whole
560 certificate chain should be checked.
561
562 The certificates are checked in issuing order, starting with the peer's
563 own certificate, then its issuer's certificate, and so on.
564
565 \sa peerVerifyDepth(), setPeerVerifyMode()
566*/
567void QSslSocket::setPeerVerifyDepth(int depth)
568{
569 Q_D(QSslSocket);
570 if (depth < 0) {
571 qWarning("QSslSocket::setPeerVerifyDepth: cannot set negative depth of %d", depth);
572 return;
573 }
574 d->configuration.peerVerifyDepth = depth;
575}
576
577/*!
578 \reimp
579
580 Returns the number of decrypted bytes that are immediately available for
581 reading.
582*/
583qint64 QSslSocket::bytesAvailable() const
584{
585 Q_D(const QSslSocket);
586 if (d->mode == UnencryptedMode)
587 return QIODevice::bytesAvailable() + (d->plainSocket ? d->plainSocket->bytesAvailable() : 0);
588 return QIODevice::bytesAvailable() + d->readBuffer.size();
589}
590
591/*!
592 \reimp
593
594 Returns the number of unencrypted bytes that are waiting to be encrypted
595 and written to the network.
596*/
597qint64 QSslSocket::bytesToWrite() const
598{
599 Q_D(const QSslSocket);
600 if (d->mode == UnencryptedMode)
601 return d->plainSocket ? d->plainSocket->bytesToWrite() : 0;
602 return d->writeBuffer.size();
603}
604
605/*!
606 \since 4.4
607
608 Returns the number of encrypted bytes that are awaiting decryption.
609 Normally, this function will return 0 because QSslSocket decrypts its
610 incoming data as soon as it can.
611*/
612qint64 QSslSocket::encryptedBytesAvailable() const
613{
614 Q_D(const QSslSocket);
615 if (d->mode == UnencryptedMode)
616 return 0;
617 return d->plainSocket->bytesAvailable();
618}
619
620/*!
621 \since 4.4
622
623 Returns the number of encrypted bytes that are waiting to be written to
624 the network.
625*/
626qint64 QSslSocket::encryptedBytesToWrite() const
627{
628 Q_D(const QSslSocket);
629 if (d->mode == UnencryptedMode)
630 return 0;
631 return d->plainSocket->bytesToWrite();
632}
633
634/*!
635 \reimp
636
637 Returns true if you can read one while line (terminated by a single ASCII
638 '\n' character) of decrypted characters; otherwise, false is returned.
639*/
640bool QSslSocket::canReadLine() const
641{
642 Q_D(const QSslSocket);
643 if (d->mode == UnencryptedMode)
644 return QIODevice::canReadLine() || (d->plainSocket && d->plainSocket->canReadLine());
645 return QIODevice::canReadLine() || (!d->readBuffer.isEmpty() && d->readBuffer.canReadLine());
646}
647
648/*!
649 \reimp
650*/
651void QSslSocket::close()
652{
653#ifdef QSSLSOCKET_DEBUG
654 qDebug() << "QSslSocket::close()";
655#endif
656 QTcpSocket::close();
657}
658
659/*!
660 \reimp
661*/
662bool QSslSocket::atEnd() const
663{
664 Q_D(const QSslSocket);
665 if (d->mode == UnencryptedMode)
666 return QIODevice::atEnd() && (!d->plainSocket || d->plainSocket->atEnd());
667 return QIODevice::atEnd() && d->readBuffer.isEmpty();
668}
669
670/*!
671 This function writes as much as possible from the internal write buffer to
672 the underlying network socket, without blocking. If any data was written,
673 this function returns true; otherwise false is returned.
674
675 Call this function if you need QSslSocket to start sending buffered data
676 immediately. The number of bytes successfully written depends on the
677 operating system. In most cases, you do not need to call this function,
678 because QAbstractSocket will start sending data automatically once control
679 goes back to the event loop. In the absence of an event loop, call
680 waitForBytesWritten() instead.
681
682 \sa write(), waitForBytesWritten()
683*/
684// Note! docs copied from QAbstractSocket::flush()
685bool QSslSocket::flush()
686{
687 Q_D(QSslSocket);
688#ifdef QSSLSOCKET_DEBUG
689 qDebug() << "QSslSocket::flush()";
690#endif
691 if (d->mode != UnencryptedMode)
692 // encrypt any unencrypted bytes in our buffer
693 d->transmit();
694
695 return d->plainSocket ? d->plainSocket->flush() : false;
696}
697
698/*!
699 \since 4.4
700
701 Sets the size of QSslSocket's internal read buffer to be \a size bytes.
702*/
703void QSslSocket::setReadBufferSize(qint64 size)
704{
705 Q_D(QSslSocket);
706 d->readBufferMaxSize = size;
707
708 // set the plain socket's buffer size to 1k if we have a limit
709 // see also the same logic in QSslSocketPrivate::createPlainSocket
710 if (d->plainSocket) {
711 if (d->mode == UnencryptedMode)
712 d->plainSocket->setReadBufferSize(size);
713 else
714 d->plainSocket->setReadBufferSize(size ? 1024 : 0);
715 }
716}
717
718/*!
719 Aborts the current connection and resets the socket. Unlike
720 disconnectFromHost(), this function immediately closes the socket,
721 clearing any pending data in the write buffer.
722
723 \sa disconnectFromHost(), close()
724*/
725void QSslSocket::abort()
726{
727 Q_D(QSslSocket);
728#ifdef QSSLSOCKET_DEBUG
729 qDebug() << "QSslSocket::abort()";
730#endif
731 if (d->plainSocket)
732 d->plainSocket->abort();
733 close();
734}
735
736/*!
737 \since 4.4
738
739 Returns the socket's SSL configuration state. The default SSL
740 configuration of a socket is to use the default ciphers,
741 default CA certificates, no local private key or certificate.
742
743 The SSL configuration also contains fields that can change with
744 time without notice.
745
746 \sa localCertificate(), peerCertificate(), peerCertificateChain(),
747 sessionCipher(), privateKey(), ciphers(), caCertificates()
748*/
749QSslConfiguration QSslSocket::sslConfiguration() const
750{
751 Q_D(const QSslSocket);
752
753 // create a deep copy of our configuration
754 QSslConfigurationPrivate *copy = new QSslConfigurationPrivate(d->configuration);
755 copy->ref = 0; // the QSslConfiguration constructor refs up
756 copy->sessionCipher = d->sessionCipher();
757
758 return QSslConfiguration(copy);
759}
760
761/*!
762 \since 4.4
763
764 Sets the socket's SSL configuration to be the contents of \a configuration.
765 This function sets the local certificate, the ciphers, the private key and the CA
766 certificates to those stored in \a configuration.
767
768 It is not possible to set the SSL-state related fields.
769
770 \sa setLocalCertificate(), setPrivateKey(), setCaCertificates(), setCiphers()
771*/
772void QSslSocket::setSslConfiguration(const QSslConfiguration &configuration)
773{
774 Q_D(QSslSocket);
775 d->configuration.localCertificate = configuration.localCertificate();
776 d->configuration.privateKey = configuration.privateKey();
777 d->configuration.ciphers = configuration.ciphers();
778 d->configuration.caCertificates = configuration.caCertificates();
779 d->configuration.peerVerifyDepth = configuration.peerVerifyDepth();
780 d->configuration.peerVerifyMode = configuration.peerVerifyMode();
781 d->configuration.protocol = configuration.protocol();
782}
783
784/*!
785 Sets the socket's local certificate to \a certificate. The local
786 certificate is necessary if you need to confirm your identity to the
787 peer. It is used together with the private key; if you set the local
788 certificate, you must also set the private key.
789
790 The local certificate and private key are always necessary for server
791 sockets, but are also rarely used by client sockets if the server requires
792 the client to authenticate.
793
794 \sa localCertificate(), setPrivateKey()
795*/
796void QSslSocket::setLocalCertificate(const QSslCertificate &certificate)
797{
798 Q_D(QSslSocket);
799 d->configuration.localCertificate = certificate;
800}
801
802/*!
803 \overload
804
805 Sets the socket's local \l {QSslCertificate} {certificate} to the
806 first one found in file \a path, which is parsed according to the
807 specified \a format.
808*/
809void QSslSocket::setLocalCertificate(const QString &path,
810 QSsl::EncodingFormat format)
811{
812 Q_D(QSslSocket);
813 QFile file(path);
814 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
815 d->configuration.localCertificate = QSslCertificate(file.readAll(), format);
816}
817
818/*!
819 Returns the socket's local \l {QSslCertificate} {certificate}, or
820 an empty certificate if no local certificate has been assigned.
821
822 \sa setLocalCertificate(), privateKey()
823*/
824QSslCertificate QSslSocket::localCertificate() const
825{
826 Q_D(const QSslSocket);
827 return d->configuration.localCertificate;
828}
829
830/*!
831 Returns the peer's digital certificate (i.e., the immediate
832 certificate of the host you are connected to), or a null
833 certificate, if the peer has not assigned a certificate.
834
835 The peer certificate is checked automatically during the
836 handshake phase, so this function is normally used to fetch
837 the certificate for display or for connection diagnostic
838 purposes. It contains information about the peer, including
839 its host name, the certificate issuer, and the peer's public
840 key.
841
842 Because the peer certificate is set during the handshake phase, it
843 is safe to access the peer certificate from a slot connected to
844 the sslErrors() signal or the encrypted() signal.
845
846 If a null certificate is returned, it can mean the SSL handshake
847 failed, or it can mean the host you are connected to doesn't have
848 a certificate, or it can mean there is no connection.
849
850 If you want to check the peer's complete chain of certificates,
851 use peerCertificateChain() to get them all at once.
852
853 \sa peerCertificateChain()
854*/
855QSslCertificate QSslSocket::peerCertificate() const
856{
857 Q_D(const QSslSocket);
858 return d->configuration.peerCertificate;
859}
860
861/*!
862 Returns the peer's chain of digital certificates, or an empty list
863 of certificates.
864
865 Peer certificates are checked automatically during the handshake
866 phase. This function is normally used to fetch certificates for
867 display, or for performing connection diagnostics. Certificates
868 contain information about the peer and the certificate issuers,
869 including host name, issuer names, and issuer public keys.
870
871 The peer certificates are set in QSslSocket during the handshake
872 phase, so it is safe to call this function from a slot connected
873 to the sslErrors() signal or the encrypted() signal.
874
875 If an empty list is returned, it can mean the SSL handshake
876 failed, or it can mean the host you are connected to doesn't have
877 a certificate, or it can mean there is no connection.
878
879 If you want to get only the peer's immediate certificate, use
880 peerCertificate().
881
882 \sa peerCertificate()
883*/
884QList<QSslCertificate> QSslSocket::peerCertificateChain() const
885{
886 Q_D(const QSslSocket);
887 return d->configuration.peerCertificateChain;
888}
889
890/*!
891 Returns the socket's cryptographic \l {QSslCipher} {cipher}, or a
892 null cipher if the connection isn't encrypted. The socket's cipher
893 for the session is set during the handshake phase. The cipher is
894 used to encrypt and decrypt data transmitted through the socket.
895
896 QSslSocket also provides functions for setting the ordered list of
897 ciphers from which the handshake phase will eventually select the
898 session cipher. This ordered list must be in place before the
899 handshake phase begins.
900
901 \sa ciphers(), setCiphers(), setDefaultCiphers(), defaultCiphers(),
902 supportedCiphers()
903*/
904QSslCipher QSslSocket::sessionCipher() const
905{
906 Q_D(const QSslSocket);
907 return d->sessionCipher();
908}
909
910/*!
911 Sets the socket's private \l {QSslKey} {key} to \a key. The
912 private key and the local \l {QSslCertificate} {certificate} are
913 used by clients and servers that must prove their identity to
914 SSL peers.
915
916 Both the key and the local certificate are required if you are
917 creating an SSL server socket. If you are creating an SSL client
918 socket, the key and local certificate are required if your client
919 must identify itself to an SSL server.
920
921 \sa privateKey(), setLocalCertificate()
922*/
923void QSslSocket::setPrivateKey(const QSslKey &key)
924{
925 Q_D(QSslSocket);
926 d->configuration.privateKey = key;
927}
928
929/*!
930 \overload
931
932 Reads the string in file \a fileName and decodes it using
933 a specified \a algorithm and encoding \a format to construct
934 an \l {QSslKey} {SSL key}. If the encoded key is encrypted,
935 \a passPhrase is used to decrypt it.
936
937 The socket's private key is set to the constructed key. The
938 private key and the local \l {QSslCertificate} {certificate} are
939 used by clients and servers that must prove their identity to SSL
940 peers.
941
942 Both the key and the local certificate are required if you are
943 creating an SSL server socket. If you are creating an SSL client
944 socket, the key and local certificate are required if your client
945 must identify itself to an SSL server.
946
947 \sa privateKey(), setLocalCertificate()
948*/
949void QSslSocket::setPrivateKey(const QString &fileName, QSsl::KeyAlgorithm algorithm,
950 QSsl::EncodingFormat format, const QByteArray &passPhrase)
951{
952 Q_D(QSslSocket);
953 QFile file(fileName);
954 if (file.open(QIODevice::ReadOnly)) {
955 d->configuration.privateKey = QSslKey(file.readAll(), algorithm,
956 format, QSsl::PrivateKey, passPhrase);
957 }
958}
959
960/*!
961 Returns this socket's private key.
962
963 \sa setPrivateKey(), localCertificate()
964*/
965QSslKey QSslSocket::privateKey() const
966{
967 Q_D(const QSslSocket);
968 return d->configuration.privateKey;
969}
970
971/*!
972 Returns this socket's current cryptographic cipher suite. This
973 list is used during the socket's handshake phase for choosing a
974 session cipher. The returned list of ciphers is ordered by
975 descending preference. (i.e., the first cipher in the list is the
976 most preferred cipher). The session cipher will be the first one
977 in the list that is also supported by the peer.
978
979 By default, the handshake phase can choose any of the ciphers
980 supported by this system's SSL libraries, which may vary from
981 system to system. The list of ciphers supported by this system's
982 SSL libraries is returned by supportedCiphers(). You can restrict
983 the list of ciphers used for choosing the session cipher for this
984 socket by calling setCiphers() with a subset of the supported
985 ciphers. You can revert to using the entire set by calling
986 setCiphers() with the list returned by supportedCiphers().
987
988 You can restrict the list of ciphers used for choosing the session
989 cipher for \e all sockets by calling setDefaultCiphers() with a
990 subset of the supported ciphers. You can revert to using the
991 entire set by calling setCiphers() with the list returned by
992 supportedCiphers().
993
994 \sa setCiphers(), defaultCiphers(), setDefaultCiphers(), supportedCiphers()
995*/
996QList<QSslCipher> QSslSocket::ciphers() const
997{
998 Q_D(const QSslSocket);
999 return d->configuration.ciphers;
1000}
1001
1002/*!
1003 Sets the cryptographic cipher suite for this socket to \a ciphers,
1004 which must contain a subset of the ciphers in the list returned by
1005 supportedCiphers().
1006
1007 Restricting the cipher suite must be done before the handshake
1008 phase, where the session cipher is chosen.
1009
1010 \sa ciphers(), setDefaultCiphers(), supportedCiphers()
1011*/
1012void QSslSocket::setCiphers(const QList<QSslCipher> &ciphers)
1013{
1014 Q_D(QSslSocket);
1015 d->configuration.ciphers = ciphers;
1016}
1017
1018/*!
1019 Sets the cryptographic cipher suite for this socket to \a ciphers, which
1020 is a colon-separated list of cipher suite names. The ciphers are listed in
1021 order of preference, starting with the most preferred cipher. For example:
1022
1023 \snippet doc/src/snippets/code/src_network_ssl_qsslsocket.cpp 4
1024
1025 Each cipher name in \a ciphers must be the name of a cipher in the
1026 list returned by supportedCiphers(). Restricting the cipher suite
1027 must be done before the handshake phase, where the session cipher
1028 is chosen.
1029
1030 \sa ciphers(), setDefaultCiphers(), supportedCiphers()
1031*/
1032void QSslSocket::setCiphers(const QString &ciphers)
1033{
1034 Q_D(QSslSocket);
1035 d->configuration.ciphers.clear();
1036 foreach (QString cipherName, ciphers.split(QLatin1String(":"),QString::SkipEmptyParts)) {
1037 for (int i = 0; i < 3; ++i) {
1038 // ### Crude
1039 QSslCipher cipher(cipherName, QSsl::SslProtocol(i));
1040 if (!cipher.isNull())
1041 d->configuration.ciphers << cipher;
1042 }
1043 }
1044}
1045
1046/*!
1047 Sets the default cryptographic cipher suite for all sockets in
1048 this application to \a ciphers, which must contain a subset of the
1049 ciphers in the list returned by supportedCiphers().
1050
1051 Restricting the default cipher suite only affects SSL sockets
1052 that perform their handshake phase after the default cipher
1053 suite has been changed.
1054
1055 \sa setCiphers(), defaultCiphers(), supportedCiphers()
1056*/
1057void QSslSocket::setDefaultCiphers(const QList<QSslCipher> &ciphers)
1058{
1059 QSslSocketPrivate::setDefaultCiphers(ciphers);
1060}
1061
1062/*!
1063 Returns the default cryptographic cipher suite for all sockets in
1064 this application. This list is used during the socket's handshake
1065 phase when negotiating with the peer to choose a session cipher.
1066 The list is ordered by preference (i.e., the first cipher in the
1067 list is the most preferred cipher).
1068
1069 By default, the handshake phase can choose any of the ciphers
1070 supported by this system's SSL libraries, which may vary from
1071 system to system. The list of ciphers supported by this system's
1072 SSL libraries is returned by supportedCiphers().
1073
1074 \sa supportedCiphers()
1075*/
1076QList<QSslCipher> QSslSocket::defaultCiphers()
1077{
1078 return QSslSocketPrivate::defaultCiphers();
1079}
1080
1081/*!
1082 Returns the list of cryptographic ciphers supported by this
1083 system. This list is set by the system's SSL libraries and may
1084 vary from system to system.
1085
1086 \sa defaultCiphers(), ciphers(), setCiphers()
1087*/
1088QList<QSslCipher> QSslSocket::supportedCiphers()
1089{
1090 return QSslSocketPrivate::supportedCiphers();
1091}
1092
1093/*!
1094 Searches all files in the \a path for certificates encoded in the
1095 specified \a format and adds them to this socket's CA certificate
1096 database. \a path can be explicit, or it can contain wildcards in
1097 the format specified by \a syntax. Returns true if one or more
1098 certificates are added to the socket's CA certificate database;
1099 otherwise returns false.
1100
1101 The CA certificate database is used by the socket during the
1102 handshake phase to validate the peer's certificate.
1103
1104 For more precise control, use addCaCertificate().
1105
1106 \sa addCaCertificate(), QSslCertificate::fromPath()
1107*/
1108bool QSslSocket::addCaCertificates(const QString &path, QSsl::EncodingFormat format,
1109 QRegExp::PatternSyntax syntax)
1110{
1111 Q_D(QSslSocket);
1112 QList<QSslCertificate> certs = QSslCertificate::fromPath(path, format, syntax);
1113 if (certs.isEmpty())
1114 return false;
1115
1116 d->configuration.caCertificates += certs;
1117 return true;
1118}
1119
1120/*!
1121 Adds the \a certificate to this socket's CA certificate database.
1122 The CA certificate database is used by the socket during the
1123 handshake phase to validate the peer's certificate.
1124
1125 To add multiple certificates, use addCaCertificates().
1126
1127 \sa caCertificates(), setCaCertificates()
1128*/
1129void QSslSocket::addCaCertificate(const QSslCertificate &certificate)
1130{
1131 Q_D(QSslSocket);
1132 d->configuration.caCertificates += certificate;
1133}
1134
1135/*!
1136 Adds the \a certificates to this socket's CA certificate database.
1137 The CA certificate database is used by the socket during the
1138 handshake phase to validate the peer's certificate.
1139
1140 For more precise control, use addCaCertificate().
1141
1142 \sa caCertificates(), addDefaultCaCertificate()
1143*/
1144void QSslSocket::addCaCertificates(const QList<QSslCertificate> &certificates)
1145{
1146 Q_D(QSslSocket);
1147 d->configuration.caCertificates += certificates;
1148}
1149
1150/*!
1151 Sets this socket's CA certificate database to be \a certificates.
1152 The certificate database must be set prior to the SSL handshake.
1153 The CA certificate database is used by the socket during the
1154 handshake phase to validate the peer's certificate.
1155
1156 The CA certificate database can be reset to the current default CA
1157 certificate database by calling this function with the list of CA
1158 certificates returned by defaultCaCertificates().
1159
1160 \sa defaultCaCertificates()
1161*/
1162void QSslSocket::setCaCertificates(const QList<QSslCertificate> &certificates)
1163{
1164 Q_D(QSslSocket);
1165 d->configuration.caCertificates = certificates;
1166}
1167
1168/*!
1169 Returns this socket's CA certificate database. The CA certificate
1170 database is used by the socket during the handshake phase to
1171 validate the peer's certificate. It can be moodified prior to the
1172 handshake with addCaCertificate(), addCaCertificates(), and
1173 setCaCertificates().
1174
1175 \sa addCaCertificate(), addCaCertificates(), setCaCertificates()
1176*/
1177QList<QSslCertificate> QSslSocket::caCertificates() const
1178{
1179 Q_D(const QSslSocket);
1180 return d->configuration.caCertificates;
1181}
1182
1183/*!
1184 Searches all files in the \a path for certificates with the
1185 specified \a encoding and adds them to the default CA certificate
1186 database. \a path can be an explicit file, or it can contain
1187 wildcards in the format specified by \a syntax. Returns true if
1188 any CA certificates are added to the default database.
1189
1190 Each SSL socket's CA certificate database is initialized to the
1191 default CA certificate database.
1192
1193 \sa defaultCaCertificates(), addCaCertificates(), addDefaultCaCertificate()
1194*/
1195bool QSslSocket::addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat encoding,
1196 QRegExp::PatternSyntax syntax)
1197{
1198 return QSslSocketPrivate::addDefaultCaCertificates(path, encoding, syntax);
1199}
1200
1201/*!
1202 Adds \a certificate to the default CA certificate database. Each
1203 SSL socket's CA certificate database is initialized to the default
1204 CA certificate database.
1205
1206 \sa defaultCaCertificates(), addCaCertificates()
1207*/
1208void QSslSocket::addDefaultCaCertificate(const QSslCertificate &certificate)
1209{
1210 QSslSocketPrivate::addDefaultCaCertificate(certificate);
1211}
1212
1213/*!
1214 Adds \a certificates to the default CA certificate database. Each
1215 SSL socket's CA certificate database is initialized to the default
1216 CA certificate database.
1217
1218 \sa defaultCaCertificates(), addCaCertificates()
1219*/
1220void QSslSocket::addDefaultCaCertificates(const QList<QSslCertificate> &certificates)
1221{
1222 QSslSocketPrivate::addDefaultCaCertificates(certificates);
1223}
1224
1225/*!
1226 Sets the default CA certificate database to \a certificates. The
1227 default CA certificate database is originally set to your system's
1228 default CA certificate database. If no system default database is
1229 found, Qt will provide its own default database. You can override
1230 the default CA certificate database with your own CA certificate
1231 database using this function.
1232
1233 Each SSL socket's CA certificate database is initialized to the
1234 default CA certificate database.
1235
1236 \sa addDefaultCaCertificate()
1237*/
1238void QSslSocket::setDefaultCaCertificates(const QList<QSslCertificate> &certificates)
1239{
1240 QSslSocketPrivate::setDefaultCaCertificates(certificates);
1241}
1242
1243/*!
1244 Returns the current default CA certificate database. This database
1245 is originally set to your system's default CA certificate database.
1246 If no system default database is found, Qt will provide its own
1247 default database. You can override the default CA certificate database
1248 with your own CA certificate database using setDefaultCaCertificates().
1249
1250 Each SSL socket's CA certificate database is initialized to the
1251 default CA certificate database.
1252
1253 \sa caCertificates()
1254*/
1255QList<QSslCertificate> QSslSocket::defaultCaCertificates()
1256{
1257 return QSslSocketPrivate::defaultCaCertificates();
1258}
1259
1260/*!
1261 Returns the system default CA certificate database for your
1262 system. This database is normally found in a standard place for
1263 your system. If it is not found there, Qt will provide its own
1264 default CA certificate database. The CA certificate database
1265 returned by this function is used to initialize the database
1266 returned by defaultCaCertificates(). You can replace that database
1267 with your own with setDefaultCaCertificates().
1268
1269 \sa caCertificates(), defaultCaCertificates(), setDefaultCaCertificates()
1270*/
1271QList<QSslCertificate> QSslSocket::systemCaCertificates()
1272{
1273 QSslSocketPrivate::ensureInitialized();
1274 return QSslSocketPrivate::systemCaCertificates();
1275}
1276
1277/*!
1278 Waits until the socket is connected, or \a msecs milliseconds,
1279 whichever happens first. If the connection has been established,
1280 this function returns true; otherwise it returns false.
1281
1282 \sa QAbstractSocket::waitForConnected()
1283*/
1284bool QSslSocket::waitForConnected(int msecs)
1285{
1286 Q_D(QSslSocket);
1287 if (!d->plainSocket)
1288 return false;
1289 bool retVal = d->plainSocket->waitForConnected(msecs);
1290 if (!retVal) {
1291 setSocketState(d->plainSocket->state());
1292 setSocketError(d->plainSocket->error());
1293 setErrorString(d->plainSocket->errorString());
1294 }
1295 return retVal;
1296}
1297
1298/*!
1299 Waits until the socket has completed the SSL handshake and has
1300 emitted encrypted(), or \a msecs milliseconds, whichever comes
1301 first. If encrypted() has been emitted, this function returns
1302 true; otherwise (e.g., the socket is disconnected, or the SSL
1303 handshake fails), false is returned.
1304
1305 The following example waits up to one second for the socket to be
1306 encrypted:
1307
1308 \snippet doc/src/snippets/code/src_network_ssl_qsslsocket.cpp 5
1309
1310 If msecs is -1, this function will not time out.
1311
1312 \sa startClientEncryption(), startServerEncryption(), encrypted(), isEncrypted()
1313*/
1314bool QSslSocket::waitForEncrypted(int msecs)
1315{
1316 Q_D(QSslSocket);
1317 if (!d->plainSocket || d->connectionEncrypted)
1318 return false;
1319 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1320 return false;
1321
1322 QTime stopWatch;
1323 stopWatch.start();
1324
1325 if (d->plainSocket->state() != QAbstractSocket::ConnectedState) {
1326 // Wait until we've entered connected state.
1327 if (!d->plainSocket->waitForConnected(msecs))
1328 return false;
1329 }
1330
1331 while (!d->connectionEncrypted) {
1332 // Start the handshake, if this hasn't been started yet.
1333 if (d->mode == UnencryptedMode)
1334 startClientEncryption();
1335 // Loop, waiting until the connection has been encrypted or an error
1336 // occurs.
1337 if (!d->plainSocket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed())))
1338 return false;
1339 }
1340 return d->connectionEncrypted;
1341}
1342
1343/*!
1344 \reimp
1345*/
1346bool QSslSocket::waitForReadyRead(int msecs)
1347{
1348 Q_D(QSslSocket);
1349 if (!d->plainSocket)
1350 return false;
1351 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1352 return d->plainSocket->waitForReadyRead(msecs);
1353
1354 // This function must return true if and only if readyRead() *was* emitted.
1355 // So we initialize "readyReadEmitted" to false and check if it was set to true.
1356 // waitForReadyRead() could be called recursively, so we can't use the same variable
1357 // (the inner waitForReadyRead() may fail, but the outer one still succeeded)
1358 bool readyReadEmitted = false;
1359 bool *previousReadyReadEmittedPointer = d->readyReadEmittedPointer;
1360 d->readyReadEmittedPointer = &readyReadEmitted;
1361
1362 QTime stopWatch;
1363 stopWatch.start();
1364
1365 if (!d->connectionEncrypted) {
1366 // Wait until we've entered encrypted mode, or until a failure occurs.
1367 if (!waitForEncrypted(msecs)) {
1368 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1369 return false;
1370 }
1371 }
1372
1373 if (!d->writeBuffer.isEmpty()) {
1374 // empty our cleartext write buffer first
1375 d->transmit();
1376 }
1377
1378 // test readyReadEmitted first because either operation above
1379 // (waitForEncrypted or transmit) may have set it
1380 while (!readyReadEmitted &&
1381 d->plainSocket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed()))) {
1382 }
1383
1384 d->readyReadEmittedPointer = previousReadyReadEmittedPointer;
1385 return readyReadEmitted;
1386}
1387
1388/*!
1389 \reimp
1390*/
1391bool QSslSocket::waitForBytesWritten(int msecs)
1392{
1393 Q_D(QSslSocket);
1394 if (!d->plainSocket)
1395 return false;
1396 if (d->mode == UnencryptedMode)
1397 return d->plainSocket->waitForBytesWritten(msecs);
1398
1399 QTime stopWatch;
1400 stopWatch.start();
1401
1402 if (!d->connectionEncrypted) {
1403 // Wait until we've entered encrypted mode, or until a failure occurs.
1404 if (!waitForEncrypted(msecs))
1405 return false;
1406 }
1407 if (!d->writeBuffer.isEmpty()) {
1408 // empty our cleartext write buffer first
1409 d->transmit();
1410 }
1411
1412 return d->plainSocket->waitForBytesWritten(qt_timeout_value(msecs, stopWatch.elapsed()));
1413}
1414
1415/*!
1416 Waits until the socket has disconnected or \a msecs milliseconds,
1417 whichever comes first. If the connection has been disconnected,
1418 this function returns true; otherwise it returns false.
1419
1420 \sa QAbstractSocket::waitForDisconnected()
1421*/
1422bool QSslSocket::waitForDisconnected(int msecs)
1423{
1424 Q_D(QSslSocket);
1425
1426 // require calling connectToHost() before waitForDisconnected()
1427 if (state() == UnconnectedState) {
1428 qWarning("QSslSocket::waitForDisconnected() is not allowed in UnconnectedState");
1429 return false;
1430 }
1431
1432 if (!d->plainSocket)
1433 return false;
1434 if (d->mode == UnencryptedMode)
1435 return d->plainSocket->waitForDisconnected(msecs);
1436
1437 QTime stopWatch;
1438 stopWatch.start();
1439
1440 if (!d->connectionEncrypted) {
1441 // Wait until we've entered encrypted mode, or until a failure occurs.
1442 if (!waitForEncrypted(msecs))
1443 return false;
1444 }
1445 bool retVal = d->plainSocket->waitForDisconnected(qt_timeout_value(msecs, stopWatch.elapsed()));
1446 if (!retVal) {
1447 setSocketState(d->plainSocket->state());
1448 setSocketError(d->plainSocket->error());
1449 setErrorString(d->plainSocket->errorString());
1450 }
1451 return retVal;
1452}
1453
1454/*!
1455 Returns a list of the last SSL errors that occurred. This is the
1456 same list as QSslSocket passes via the sslErrors() signal. If the
1457 connection has been encrypted with no errors, this function will
1458 return an empty list.
1459
1460 \sa connectToHostEncrypted()
1461*/
1462QList<QSslError> QSslSocket::sslErrors() const
1463{
1464 Q_D(const QSslSocket);
1465 return d->sslErrors;
1466}
1467
1468/*!
1469 Returns true if this platform supports SSL; otherwise, returns
1470 false. If the platform doesn't support SSL, the socket will fail
1471 in the connection phase.
1472*/
1473bool QSslSocket::supportsSsl()
1474{
1475 return QSslSocketPrivate::ensureInitialized();
1476}
1477
1478/*!
1479 Starts a delayed SSL handshake for a client connection. This
1480 function can be called when the socket is in the \l ConnectedState
1481 but still in the \l UnencryptedMode. If it is not yet connected,
1482 or if it is already encrypted, this function has no effect.
1483
1484 Clients that implement STARTTLS functionality often make use of
1485 delayed SSL handshakes. Most other clients can avoid calling this
1486 function directly by using connectToHostEncrypted() instead, which
1487 automatically performs the handshake.
1488
1489 \sa connectToHostEncrypted(), startServerEncryption()
1490*/
1491void QSslSocket::startClientEncryption()
1492{
1493 Q_D(QSslSocket);
1494 if (d->mode != UnencryptedMode) {
1495 qWarning("QSslSocket::startClientEncryption: cannot start handshake on non-plain connection");
1496 return;
1497 }
1498#ifdef QSSLSOCKET_DEBUG
1499 qDebug() << "QSslSocket::startClientEncryption()";
1500#endif
1501 d->mode = SslClientMode;
1502 emit modeChanged(d->mode);
1503 d->startClientEncryption();
1504}
1505
1506/*!
1507 Starts a delayed SSL handshake for a server connection. This
1508 function can be called when the socket is in the \l ConnectedState
1509 but still in \l UnencryptedMode. If it is not connected or it is
1510 already encrypted, the function has no effect.
1511
1512 For server sockets, calling this function is the only way to
1513 initiate the SSL handshake. Most servers will call this function
1514 immediately upon receiving a connection, or as a result of having
1515 received a protocol-specific command to enter SSL mode (e.g, the
1516 server may respond to receiving the string "STARTTLS\r\n" by
1517 calling this function).
1518
1519 The most common way to implement an SSL server is to create a
1520 subclass of QTcpServer and reimplement
1521 QTcpServer::incomingConnection(). The returned socket descriptor
1522 is then passed to QSslSocket::setSocketDescriptor().
1523
1524 \sa connectToHostEncrypted(), startClientEncryption()
1525*/
1526void QSslSocket::startServerEncryption()
1527{
1528 Q_D(QSslSocket);
1529 if (d->mode != UnencryptedMode) {
1530 qWarning("QSslSocket::startClientEncryption: cannot start handshake on non-plain connection");
1531 return;
1532 }
1533#ifdef QSSLSOCKET_DEBUG
1534 qDebug() << "QSslSocket::startServerEncryption()";
1535#endif
1536 d->mode = SslServerMode;
1537 emit modeChanged(d->mode);
1538 d->startServerEncryption();
1539}
1540
1541/*!
1542 This slot tells QSslSocket to ignore errors during QSslSocket's
1543 handshake phase and continue connecting. If you want to continue
1544 with the connection even if errors occur during the handshake
1545 phase, then you must call this slot, either from a slot connected
1546 to sslErrors(), or before the handshake phase. If you don't call
1547 this slot, either in response to errors or before the handshake,
1548 the connection will be dropped after the sslErrors() signal has
1549 been emitted.
1550
1551 If there are no errors during the SSL handshake phase (i.e., the
1552 identity of the peer is established with no problems), QSslSocket
1553 will not emit the sslErrors() signal, and it is unnecessary to
1554 call this function.
1555
1556 Ignoring errors that occur during an SSL handshake should be done
1557 with caution. A fundamental characteristic of secure connections
1558 is that they should be established with an error free handshake.
1559
1560 \sa sslErrors()
1561*/
1562void QSslSocket::ignoreSslErrors()
1563{
1564 Q_D(QSslSocket);
1565 d->ignoreSslErrors = true;
1566}
1567
1568/*!
1569 \internal
1570*/
1571void QSslSocket::connectToHostImplementation(const QString &hostName, quint16 port,
1572 OpenMode openMode)
1573{
1574 Q_D(QSslSocket);
1575 if (!d->initialized)
1576 d->init();
1577 d->initialized = false;
1578
1579#ifdef QSSLSOCKET_DEBUG
1580 qDebug() << "QSslSocket::connectToHostImplementation("
1581 << hostName << "," << port << "," << openMode << ")";
1582#endif
1583 if (!d->plainSocket) {
1584#ifdef QSSLSOCKET_DEBUG
1585 qDebug() << "\tcreating internal plain socket";
1586#endif
1587 d->createPlainSocket(openMode);
1588 }
1589#ifndef QT_NO_NETWORKPROXY
1590 d->plainSocket->setProxy(proxy());
1591#endif
1592 QIODevice::open(openMode);
1593 d->plainSocket->connectToHost(hostName, port, openMode);
1594 d->cachedSocketDescriptor = d->plainSocket->socketDescriptor();
1595}
1596
1597/*!
1598 \internal
1599*/
1600void QSslSocket::disconnectFromHostImplementation()
1601{
1602 Q_D(QSslSocket);
1603#ifdef QSSLSOCKET_DEBUG
1604 qDebug() << "QSslSocket::disconnectFromHostImplementation()";
1605#endif
1606 if (!d->plainSocket)
1607 return;
1608 if (d->state == UnconnectedState)
1609 return;
1610 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1611 d->plainSocket->disconnectFromHost();
1612 return;
1613 }
1614 if (d->state <= ConnectingState) {
1615 d->pendingClose = true;
1616 return;
1617 }
1618
1619 // Perhaps emit closing()
1620 if (d->state != ClosingState) {
1621 d->state = ClosingState;
1622 emit stateChanged(d->state);
1623 }
1624
1625 if (!d->writeBuffer.isEmpty())
1626 return;
1627
1628 if (d->mode == UnencryptedMode) {
1629 d->plainSocket->disconnectFromHost();
1630 } else {
1631 d->disconnectFromHost();
1632 }
1633}
1634
1635/*!
1636 \reimp
1637*/
1638qint64 QSslSocket::readData(char *data, qint64 maxlen)
1639{
1640 Q_D(QSslSocket);
1641 qint64 readBytes = 0;
1642
1643 if (d->mode == UnencryptedMode && !d->autoStartHandshake) {
1644 readBytes = d->plainSocket->read(data, maxlen);
1645 } else {
1646 do {
1647 const char *readPtr = d->readBuffer.readPointer();
1648 int bytesToRead = qMin<int>(maxlen - readBytes, d->readBuffer.nextDataBlockSize());
1649 ::memcpy(data + readBytes, readPtr, bytesToRead);
1650 readBytes += bytesToRead;
1651 d->readBuffer.free(bytesToRead);
1652 } while (!d->readBuffer.isEmpty() && readBytes < maxlen);
1653 }
1654#ifdef QSSLSOCKET_DEBUG
1655 qDebug() << "QSslSocket::readData(" << (void *)data << "," << maxlen << ") ==" << readBytes;
1656#endif
1657 return readBytes;
1658}
1659
1660/*!
1661 \reimp
1662*/
1663qint64 QSslSocket::writeData(const char *data, qint64 len)
1664{
1665 Q_D(QSslSocket);
1666#ifdef QSSLSOCKET_DEBUG
1667 qDebug() << "QSslSocket::writeData(" << (void *)data << "," << len << ")";
1668#endif
1669 if (d->mode == UnencryptedMode && !d->autoStartHandshake)
1670 return d->plainSocket->write(data, len);
1671
1672 char *writePtr = d->writeBuffer.reserve(len);
1673 ::memcpy(writePtr, data, len);
1674
1675 // make sure we flush to the plain socket's buffer
1676 QMetaObject::invokeMethod(this, "_q_flushWriteBuffer", Qt::QueuedConnection);
1677
1678 return len;
1679}
1680
1681/*!
1682 \internal
1683*/
1684QSslSocketPrivate::QSslSocketPrivate()
1685 : initialized(false), readyReadEmittedPointer(0), plainSocket(0)
1686{
1687 QSslConfigurationPrivate::deepCopyDefaultConfiguration(&configuration);
1688}
1689
1690/*!
1691 \internal
1692*/
1693QSslSocketPrivate::~QSslSocketPrivate()
1694{
1695}
1696
1697/*!
1698 \internal
1699*/
1700void QSslSocketPrivate::init()
1701{
1702 mode = QSslSocket::UnencryptedMode;
1703 autoStartHandshake = false;
1704 connectionEncrypted = false;
1705 ignoreSslErrors = false;
1706
1707 readBuffer.clear();
1708 writeBuffer.clear();
1709 configuration.peerCertificate.clear();
1710 configuration.peerCertificateChain.clear();
1711}
1712
1713/*!
1714 \internal
1715*/
1716QList<QSslCipher> QSslSocketPrivate::defaultCiphers()
1717{
1718 QMutexLocker locker(&globalData()->mutex);
1719 return globalData()->config->ciphers;
1720}
1721
1722/*!
1723 \internal
1724*/
1725QList<QSslCipher> QSslSocketPrivate::supportedCiphers()
1726{
1727 QSslSocketPrivate::ensureInitialized();
1728 QMutexLocker locker(&globalData()->mutex);
1729 return globalData()->supportedCiphers;
1730}
1731
1732/*!
1733 \internal
1734*/
1735void QSslSocketPrivate::setDefaultCiphers(const QList<QSslCipher> &ciphers)
1736{
1737 QMutexLocker locker(&globalData()->mutex);
1738 globalData()->config.detach();
1739 globalData()->config->ciphers = ciphers;
1740}
1741
1742/*!
1743 \internal
1744*/
1745void QSslSocketPrivate::setDefaultSupportedCiphers(const QList<QSslCipher> &ciphers)
1746{
1747 QMutexLocker locker(&globalData()->mutex);
1748 globalData()->config.detach();
1749 globalData()->supportedCiphers = ciphers;
1750}
1751
1752/*!
1753 \internal
1754*/
1755QList<QSslCertificate> QSslSocketPrivate::defaultCaCertificates()
1756{
1757 QSslSocketPrivate::ensureInitialized();
1758 QMutexLocker locker(&globalData()->mutex);
1759 return globalData()->config->caCertificates;
1760}
1761
1762/*!
1763 \internal
1764*/
1765void QSslSocketPrivate::setDefaultCaCertificates(const QList<QSslCertificate> &certs)
1766{
1767 QSslSocketPrivate::ensureInitialized();
1768 QMutexLocker locker(&globalData()->mutex);
1769 globalData()->config.detach();
1770 globalData()->config->caCertificates = certs;
1771}
1772
1773/*!
1774 \internal
1775*/
1776bool QSslSocketPrivate::addDefaultCaCertificates(const QString &path, QSsl::EncodingFormat format,
1777 QRegExp::PatternSyntax syntax)
1778{
1779 QSslSocketPrivate::ensureInitialized();
1780 QList<QSslCertificate> certs = QSslCertificate::fromPath(path, format, syntax);
1781 if (certs.isEmpty())
1782 return false;
1783
1784 QMutexLocker locker(&globalData()->mutex);
1785 globalData()->config.detach();
1786 globalData()->config->caCertificates += certs;
1787 return true;
1788}
1789
1790/*!
1791 \internal
1792*/
1793void QSslSocketPrivate::addDefaultCaCertificate(const QSslCertificate &cert)
1794{
1795 QSslSocketPrivate::ensureInitialized();
1796 QMutexLocker locker(&globalData()->mutex);
1797 globalData()->config.detach();
1798 globalData()->config->caCertificates += cert;
1799}
1800
1801/*!
1802 \internal
1803*/
1804void QSslSocketPrivate::addDefaultCaCertificates(const QList<QSslCertificate> &certs)
1805{
1806 QSslSocketPrivate::ensureInitialized();
1807 QMutexLocker locker(&globalData()->mutex);
1808 globalData()->config.detach();
1809 globalData()->config->caCertificates += certs;
1810}
1811
1812/*!
1813 \internal
1814*/
1815QSslConfiguration QSslConfigurationPrivate::defaultConfiguration()
1816{
1817 QSslSocketPrivate::ensureInitialized();
1818 QMutexLocker locker(&globalData()->mutex);
1819 return QSslConfiguration(globalData()->config.data());
1820}
1821
1822/*!
1823 \internal
1824*/
1825void QSslConfigurationPrivate::setDefaultConfiguration(const QSslConfiguration &configuration)
1826{
1827 QSslSocketPrivate::ensureInitialized();
1828 QMutexLocker locker(&globalData()->mutex);
1829 if (globalData()->config == configuration.d)
1830 return; // nothing to do
1831
1832 globalData()->config = const_cast<QSslConfigurationPrivate*>(configuration.d.constData());
1833}
1834
1835/*!
1836 \internal
1837*/
1838void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPrivate *ptr)
1839{
1840 QSslSocketPrivate::ensureInitialized();
1841 QMutexLocker locker(&globalData()->mutex);
1842 const QSslConfigurationPrivate *global = globalData()->config.constData();
1843
1844 ptr->ref = 1;
1845 ptr->peerCertificate = global->peerCertificate;
1846 ptr->peerCertificateChain = global->peerCertificateChain;
1847 ptr->localCertificate = global->localCertificate;
1848 ptr->privateKey = global->privateKey;
1849 ptr->sessionCipher = global->sessionCipher;
1850 ptr->ciphers = global->ciphers;
1851 ptr->caCertificates = global->caCertificates;
1852 ptr->protocol = global->protocol;
1853 ptr->peerVerifyMode = global->peerVerifyMode;
1854 ptr->peerVerifyDepth = global->peerVerifyDepth;
1855}
1856
1857/*!
1858 \internal
1859*/
1860void QSslSocketPrivate::createPlainSocket(QIODevice::OpenMode openMode)
1861{
1862 Q_Q(QSslSocket);
1863 q->setOpenMode(openMode); // <- from QIODevice
1864 q->setSocketState(QAbstractSocket::UnconnectedState);
1865 q->setSocketError(QAbstractSocket::UnknownSocketError);
1866 q->setLocalPort(0);
1867 q->setLocalAddress(QHostAddress());
1868 q->setPeerPort(0);
1869 q->setPeerAddress(QHostAddress());
1870 q->setPeerName(QString());
1871
1872 plainSocket = new QTcpSocket(q);
1873 q->connect(plainSocket, SIGNAL(connected()),
1874 q, SLOT(_q_connectedSlot()),
1875 Qt::DirectConnection);
1876 q->connect(plainSocket, SIGNAL(hostFound()),
1877 q, SLOT(_q_hostFoundSlot()),
1878 Qt::DirectConnection);
1879 q->connect(plainSocket, SIGNAL(disconnected()),
1880 q, SLOT(_q_disconnectedSlot()),
1881 Qt::DirectConnection);
1882 q->connect(plainSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
1883 q, SLOT(_q_stateChangedSlot(QAbstractSocket::SocketState)),
1884 Qt::DirectConnection);
1885 q->connect(plainSocket, SIGNAL(error(QAbstractSocket::SocketError)),
1886 q, SLOT(_q_errorSlot(QAbstractSocket::SocketError)),
1887 Qt::DirectConnection);
1888 q->connect(plainSocket, SIGNAL(readyRead()),
1889 q, SLOT(_q_readyReadSlot()),
1890 Qt::DirectConnection);
1891 q->connect(plainSocket, SIGNAL(bytesWritten(qint64)),
1892 q, SLOT(_q_bytesWrittenSlot(qint64)),
1893 Qt::DirectConnection);
1894#ifndef QT_NO_NETWORKPROXY
1895 q->connect(plainSocket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
1896 q, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
1897#endif
1898
1899 readBuffer.clear();
1900 writeBuffer.clear();
1901 connectionEncrypted = false;
1902 configuration.peerCertificate.clear();
1903 configuration.peerCertificateChain.clear();
1904 mode = QSslSocket::UnencryptedMode;
1905 q->setReadBufferSize(readBufferMaxSize);
1906}
1907
1908/*!
1909 \internal
1910*/
1911void QSslSocketPrivate::_q_connectedSlot()
1912{
1913 Q_Q(QSslSocket);
1914 q->setLocalPort(plainSocket->localPort());
1915 q->setLocalAddress(plainSocket->localAddress());
1916 q->setPeerPort(plainSocket->peerPort());
1917 q->setPeerAddress(plainSocket->peerAddress());
1918 q->setPeerName(plainSocket->peerName());
1919 cachedSocketDescriptor = plainSocket->socketDescriptor();
1920
1921#ifdef QSSLSOCKET_DEBUG
1922 qDebug() << "QSslSocket::_q_connectedSlot()";
1923 qDebug() << "\tstate =" << q->state();
1924 qDebug() << "\tpeer =" << q->peerName() << q->peerAddress() << q->peerPort();
1925 qDebug() << "\tlocal =" << QHostInfo::fromName(q->localAddress().toString()).hostName()
1926 << q->localAddress() << q->localPort();
1927#endif
1928 emit q->connected();
1929
1930 if (autoStartHandshake) {
1931 q->startClientEncryption();
1932 } else if (pendingClose) {
1933 pendingClose = false;
1934 q->disconnectFromHost();
1935 }
1936}
1937
1938/*!
1939 \internal
1940*/
1941void QSslSocketPrivate::_q_hostFoundSlot()
1942{
1943 Q_Q(QSslSocket);
1944#ifdef QSSLSOCKET_DEBUG
1945 qDebug() << "QSslSocket::_q_hostFoundSlot()";
1946 qDebug() << "\tstate =" << q->state();
1947#endif
1948 emit q->hostFound();
1949}
1950
1951/*!
1952 \internal
1953*/
1954void QSslSocketPrivate::_q_disconnectedSlot()
1955{
1956 Q_Q(QSslSocket);
1957#ifdef QSSLSOCKET_DEBUG
1958 qDebug() << "QSslSocket::_q_disconnectedSlot()";
1959 qDebug() << "\tstate =" << q->state();
1960#endif
1961 disconnected();
1962 emit q->disconnected();
1963}
1964
1965/*!
1966 \internal
1967*/
1968void QSslSocketPrivate::_q_stateChangedSlot(QAbstractSocket::SocketState state)
1969{
1970 Q_Q(QSslSocket);
1971#ifdef QSSLSOCKET_DEBUG
1972 qDebug() << "QSslSocket::_q_stateChangedSlot(" << state << ")";
1973#endif
1974 q->setSocketState(state);
1975 emit q->stateChanged(state);
1976}
1977
1978/*!
1979 \internal
1980*/
1981void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error)
1982{
1983 Q_Q(QSslSocket);
1984#ifdef QSSLSOCKET_DEBUG
1985 qDebug() << "QSslSocket::_q_errorSlot(" << error << ")";
1986 qDebug() << "\tstate =" << q->state();
1987 qDebug() << "\terrorString =" << q->errorString();
1988#endif
1989 q->setSocketError(plainSocket->error());
1990 q->setErrorString(plainSocket->errorString());
1991 emit q->error(error);
1992}
1993
1994/*!
1995 \internal
1996*/
1997void QSslSocketPrivate::_q_readyReadSlot()
1998{
1999 Q_Q(QSslSocket);
2000#ifdef QSSLSOCKET_DEBUG
2001 qDebug() << "QSslSocket::_q_readyReadSlot() -" << plainSocket->bytesAvailable() << "bytes available";
2002#endif
2003 if (mode == QSslSocket::UnencryptedMode) {
2004 if (readyReadEmittedPointer)
2005 *readyReadEmittedPointer = true;
2006 emit q->readyRead();
2007 return;
2008 }
2009
2010 transmit();
2011}
2012
2013/*!
2014 \internal
2015*/
2016void QSslSocketPrivate::_q_bytesWrittenSlot(qint64 written)
2017{
2018 Q_Q(QSslSocket);
2019#ifdef QSSLSOCKET_DEBUG
2020 qDebug() << "QSslSocket::_q_bytesWrittenSlot(" << written << ")";
2021#endif
2022
2023 if (mode == QSslSocket::UnencryptedMode)
2024 emit q->bytesWritten(written);
2025 else
2026 emit q->encryptedBytesWritten(written);
2027 if (state == QAbstractSocket::ClosingState && writeBuffer.isEmpty())
2028 q->disconnectFromHost();
2029}
2030
2031/*!
2032 \internal
2033*/
2034void QSslSocketPrivate::_q_flushWriteBuffer()
2035{
2036 Q_Q(QSslSocket);
2037 if (!writeBuffer.isEmpty())
2038 q->flush();
2039}
2040
2041QT_END_NAMESPACE
2042
2043// For private slots
2044#define d d_ptr
2045#include "moc_qsslsocket.cpp"
Note: See TracBrowser for help on using the repository browser.