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