Fix windows cert fetcher if site presents full chain
[profile/ivi/qtbase.git] / src / network / ssl / qsslsocket_openssl.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 //#define QSSLSOCKET_DEBUG
43
44 #include "qsslsocket_openssl_p.h"
45 #include "qsslsocket_openssl_symbols_p.h"
46 #include "qsslsocket.h"
47 #include "qsslcertificate_p.h"
48 #include "qsslcipher_p.h"
49
50 #include <QtCore/qdatetime.h>
51 #include <QtCore/qdebug.h>
52 #include <QtCore/qdir.h>
53 #include <QtCore/qdiriterator.h>
54 #include <QtCore/qelapsedtimer.h>
55 #include <QtCore/qfile.h>
56 #include <QtCore/qfileinfo.h>
57 #include <QtCore/qmutex.h>
58 #include <QtCore/qthread.h>
59 #include <QtCore/qurl.h>
60 #include <QtCore/qvarlengtharray.h>
61 #include <QLibrary> // for loading the security lib for the CA store
62
63 #ifdef Q_OS_WIN
64 Q_DECLARE_METATYPE(QSslCertificate);
65 #endif
66
67 QT_BEGIN_NAMESPACE
68
69 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
70 #define kSecTrustSettingsDomainSystem 2 // so we do not need to include the header file
71     PtrSecCertificateGetData QSslSocketPrivate::ptrSecCertificateGetData = 0;
72     PtrSecTrustSettingsCopyCertificates QSslSocketPrivate::ptrSecTrustSettingsCopyCertificates = 0;
73     PtrSecTrustCopyAnchorCertificates QSslSocketPrivate::ptrSecTrustCopyAnchorCertificates = 0;
74 #elif defined(Q_OS_WIN)
75     PtrCertOpenSystemStoreW QSslSocketPrivate::ptrCertOpenSystemStoreW = 0;
76     PtrCertFindCertificateInStore QSslSocketPrivate::ptrCertFindCertificateInStore = 0;
77     PtrCertCloseStore QSslSocketPrivate::ptrCertCloseStore = 0;
78 #endif
79
80 bool QSslSocketPrivate::s_libraryLoaded = false;
81 bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
82 bool QSslSocketPrivate::s_loadRootCertsOnDemand = false;
83
84 /* \internal
85
86     From OpenSSL's thread(3) manual page:
87
88     OpenSSL can safely be used in multi-threaded applications provided that at
89     least two callback functions are set.
90
91     locking_function(int mode, int n, const char *file, int line) is needed to
92     perform locking on shared data structures.  (Note that OpenSSL uses a
93     number of global data structures that will be implicitly shared
94     when-whenever ever multiple threads use OpenSSL.)  Multi-threaded
95     applications will crash at random if it is not set.  ...
96     ...
97     id_function(void) is a function that returns a thread ID. It is not
98     needed on Windows nor on platforms where getpid() returns a different
99     ID for each thread (most notably Linux)
100 */
101 class QOpenSslLocks
102 {
103 public:
104     inline QOpenSslLocks()
105         : initLocker(QMutex::Recursive),
106           locksLocker(QMutex::Recursive)
107     {
108         QMutexLocker locker(&locksLocker);
109         int numLocks = q_CRYPTO_num_locks();
110         locks = new QMutex *[numLocks];
111         memset(locks, 0, numLocks * sizeof(QMutex *));
112     }
113     inline ~QOpenSslLocks()
114     {
115         QMutexLocker locker(&locksLocker);
116         for (int i = 0; i < q_CRYPTO_num_locks(); ++i)
117             delete locks[i];
118         delete [] locks;
119
120         QSslSocketPrivate::deinitialize();
121     }
122     inline QMutex *lock(int num)
123     {
124         QMutexLocker locker(&locksLocker);
125         QMutex *tmp = locks[num];
126         if (!tmp)
127             tmp = locks[num] = new QMutex(QMutex::Recursive);
128         return tmp;
129     }
130
131     QMutex *globalLock()
132     {
133         return &locksLocker;
134     }
135
136     QMutex *initLock()
137     {
138         return &initLocker;
139     }
140
141 private:
142     QMutex initLocker;
143     QMutex locksLocker;
144     QMutex **locks;
145 };
146 Q_GLOBAL_STATIC(QOpenSslLocks, openssl_locks)
147
148 extern "C" {
149 static void locking_function(int mode, int lockNumber, const char *, int)
150 {
151     QMutex *mutex = openssl_locks()->lock(lockNumber);
152
153     // Lock or unlock it
154     if (mode & CRYPTO_LOCK)
155         mutex->lock();
156     else
157         mutex->unlock();
158 }
159 static unsigned long id_function()
160 {
161     return (quintptr)QThread::currentThreadId();
162 }
163 } // extern "C"
164
165 QSslSocketBackendPrivate::QSslSocketBackendPrivate()
166     : ssl(0),
167       ctx(0),
168       pkey(0),
169       readBio(0),
170       writeBio(0),
171       session(0)
172 {
173     // Calls SSL_library_init().
174     ensureInitialized();
175 }
176
177 QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
178 {
179     destroySslContext();
180 }
181
182 QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(SSL_CIPHER *cipher)
183 {
184     QSslCipher ciph;
185
186     char buf [256];
187     QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
188
189     QStringList descriptionList = descriptionOneLine.split(QLatin1String(" "), QString::SkipEmptyParts);
190     if (descriptionList.size() > 5) {
191         // ### crude code.
192         ciph.d->isNull = false;
193         ciph.d->name = descriptionList.at(0);
194
195         QString protoString = descriptionList.at(1);
196         ciph.d->protocolString = protoString;
197         ciph.d->protocol = QSsl::UnknownProtocol;
198         if (protoString == QLatin1String("SSLv3"))
199             ciph.d->protocol = QSsl::SslV3;
200         else if (protoString == QLatin1String("SSLv2"))
201             ciph.d->protocol = QSsl::SslV2;
202         else if (protoString == QLatin1String("TLSv1"))
203             ciph.d->protocol = QSsl::TlsV1_0;
204
205         if (descriptionList.at(2).startsWith(QLatin1String("Kx=")))
206             ciph.d->keyExchangeMethod = descriptionList.at(2).mid(3);
207         if (descriptionList.at(3).startsWith(QLatin1String("Au=")))
208             ciph.d->authenticationMethod = descriptionList.at(3).mid(3);
209         if (descriptionList.at(4).startsWith(QLatin1String("Enc=")))
210             ciph.d->encryptionMethod = descriptionList.at(4).mid(4);
211         ciph.d->exportable = (descriptionList.size() > 6 && descriptionList.at(6) == QLatin1String("export"));
212
213         ciph.d->bits = cipher->strength_bits;
214         ciph.d->supportedBits = cipher->alg_bits;
215
216     }
217     return ciph;
218 }
219
220 // ### This list is shared between all threads, and protected by a
221 // mutex. Investigate using thread local storage instead.
222 struct QSslErrorList
223 {
224     QMutex mutex;
225     QList<QPair<int, int> > errors;
226 };
227 Q_GLOBAL_STATIC(QSslErrorList, _q_sslErrorList)
228 static int q_X509Callback(int ok, X509_STORE_CTX *ctx)
229 {
230     if (!ok) {
231         // Store the error and at which depth the error was detected.
232         _q_sslErrorList()->errors << qMakePair<int, int>(ctx->error, ctx->error_depth);
233 #ifdef QSSLSOCKET_DEBUG
234         qDebug() << "verification error: dumping bad certificate";
235         qDebug() << QSslCertificatePrivate::QSslCertificate_from_X509(ctx->current_cert).toPem();
236         qDebug() << "dumping chain";
237         foreach (QSslCertificate cert, QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(ctx->chain)) {
238             QString certFormat(QStringLiteral("O=%1 CN=%2 L=%3 OU=%4 C=%5 ST=%6"));
239             qDebug() << "Issuer:" << "O=" << cert.issuerInfo(QSslCertificate::Organization)
240                 << "CN=" << cert.issuerInfo(QSslCertificate::CommonName)
241                 << "L=" << cert.issuerInfo(QSslCertificate::LocalityName)
242                 << "OU=" << cert.issuerInfo(QSslCertificate::OrganizationalUnitName)
243                 << "C=" << cert.issuerInfo(QSslCertificate::CountryName)
244                 << "ST=" << cert.issuerInfo(QSslCertificate::StateOrProvinceName);
245             qDebug() << "Subject:" << "O=" << cert.subjectInfo(QSslCertificate::Organization)
246                 << "CN=" << cert.subjectInfo(QSslCertificate::CommonName)
247                 << "L=" << cert.subjectInfo(QSslCertificate::LocalityName)
248                 << "OU=" << cert.subjectInfo(QSslCertificate::OrganizationalUnitName)
249                 << "C=" << cert.subjectInfo(QSslCertificate::CountryName)
250                 << "ST=" << cert.subjectInfo(QSslCertificate::StateOrProvinceName);
251             qDebug() << "Valid:" << cert.effectiveDate() << "-" << cert.expiryDate();
252         }
253 #endif
254     }
255     // Always return OK to allow verification to continue. We're handle the
256     // errors gracefully after collecting all errors, after verification has
257     // completed.
258     return 1;
259 }
260
261 long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, QSsl::SslOptions sslOptions)
262 {
263     long options;
264     if (protocol == QSsl::TlsV1SslV3 || protocol == QSsl::SecureProtocols)
265         options = SSL_OP_ALL|SSL_OP_NO_SSLv2;
266     else
267         options = SSL_OP_ALL;
268
269     // This option is disabled by default, so we need to be able to clear it
270     if (sslOptions & QSsl::SslOptionDisableEmptyFragments)
271         options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
272     else
273         options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
274
275 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
276     // This option is disabled by default, so we need to be able to clear it
277     if (sslOptions & QSsl::SslOptionDisableLegacyRenegotiation)
278         options &= ~SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
279     else
280         options |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
281 #endif
282
283 #ifdef SSL_OP_NO_TICKET
284     if (sslOptions & QSsl::SslOptionDisableSessionTickets)
285         options |= SSL_OP_NO_TICKET;
286 #endif
287 #ifdef SSL_OP_NO_COMPRESSION
288     if (sslOptions & QSsl::SslOptionDisableCompression)
289         options |= SSL_OP_NO_COMPRESSION;
290 #endif
291
292     return options;
293 }
294
295 bool QSslSocketBackendPrivate::initSslContext()
296 {
297     Q_Q(QSslSocket);
298
299     // Create and initialize SSL context. Accept SSLv2, SSLv3 and TLSv1_0.
300     bool client = (mode == QSslSocket::SslClientMode);
301
302     bool reinitialized = false;
303
304 init_context:
305     switch (configuration.protocol) {
306     case QSsl::SslV2:
307 #ifndef OPENSSL_NO_SSL2
308         ctx = q_SSL_CTX_new(client ? q_SSLv2_client_method() : q_SSLv2_server_method());
309 #else
310         ctx = 0; // SSL 2 not supported by the system, but chosen deliberately -> error
311 #endif
312         break;
313     case QSsl::SslV3:
314         ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method());
315         break;
316     case QSsl::SecureProtocols: // SslV2 will be disabled below
317     case QSsl::TlsV1SslV3: // SslV2 will be disabled below
318     case QSsl::AnyProtocol:
319     default:
320         ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method());
321         break;
322     case QSsl::TlsV1_0:
323         ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method());
324         break;
325     }
326     if (!ctx) {
327         // After stopping Flash 10 the SSL library looses its ciphers. Try re-adding them
328         // by re-initializing the library.
329         if (!reinitialized) {
330             reinitialized = true;
331             if (q_SSL_library_init() == 1)
332                 goto init_context;
333         }
334
335         q->setErrorString(QSslSocket::tr("Error creating SSL context (%1)").arg(getErrorsFromOpenSsl()));
336         q->setSocketError(QAbstractSocket::SslInternalError);
337         emit q->error(QAbstractSocket::SslInternalError);
338         return false;
339     }
340
341     // Enable bug workarounds.
342     long options = setupOpenSslOptions(configuration.protocol, configuration.sslOptions);
343     q_SSL_CTX_set_options(ctx, options);
344
345 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
346     // Tell OpenSSL to release memory early
347     // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html
348     if (q_SSLeay() >= 0x10000000L)
349         q_SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
350 #endif
351
352     // Initialize ciphers
353     QByteArray cipherString;
354     int first = true;
355     QList<QSslCipher> ciphers = configuration.ciphers;
356     if (ciphers.isEmpty())
357         ciphers = defaultCiphers();
358     foreach (const QSslCipher &cipher, ciphers) {
359         if (first)
360             first = false;
361         else
362             cipherString.append(':');
363         cipherString.append(cipher.name().toLatin1());
364     }
365
366     if (!q_SSL_CTX_set_cipher_list(ctx, cipherString.data())) {
367         q->setErrorString(QSslSocket::tr("Invalid or empty cipher list (%1)").arg(getErrorsFromOpenSsl()));
368         q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
369         emit q->error(QAbstractSocket::SslInvalidUserDataError);
370         return false;
371     }
372
373     // Add all our CAs to this store.
374     QList<QSslCertificate> expiredCerts;
375     foreach (const QSslCertificate &caCertificate, q->caCertificates()) {
376         // add expired certs later, so that the
377         // valid ones are used before the expired ones
378         if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
379             expiredCerts.append(caCertificate);
380         } else {
381             q_X509_STORE_add_cert(ctx->cert_store, reinterpret_cast<X509 *>(caCertificate.handle()));
382         }
383     }
384
385     bool addExpiredCerts = true;
386 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
387     //On Leopard SSL does not work if we add the expired certificates.
388     if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
389        addExpiredCerts = false;
390 #endif
391     // now add the expired certs
392     if (addExpiredCerts) {
393         foreach (const QSslCertificate &caCertificate, expiredCerts) {
394             q_X509_STORE_add_cert(ctx->cert_store, reinterpret_cast<X509 *>(caCertificate.handle()));
395         }
396     }
397
398     if (s_loadRootCertsOnDemand && allowRootCertOnDemandLoading) {
399         // tell OpenSSL the directories where to look up the root certs on demand
400         QList<QByteArray> unixDirs = unixRootCertDirectories();
401         for (int a = 0; a < unixDirs.count(); ++a)
402             q_SSL_CTX_load_verify_locations(ctx, 0, unixDirs.at(a).constData());
403     }
404
405     // Register a custom callback to get all verification errors.
406     X509_STORE_set_verify_cb_func(ctx->cert_store, q_X509Callback);
407
408     if (!configuration.localCertificate.isNull()) {
409         // Require a private key as well.
410         if (configuration.privateKey.isNull()) {
411             q->setErrorString(QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(getErrorsFromOpenSsl()));
412             q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
413             emit q->error(QAbstractSocket::SslInvalidUserDataError);
414             return false;
415         }
416
417         // Load certificate
418         if (!q_SSL_CTX_use_certificate(ctx, reinterpret_cast<X509 *>(configuration.localCertificate.handle()))) {
419             q->setErrorString(QSslSocket::tr("Error loading local certificate, %1").arg(getErrorsFromOpenSsl()));
420             q->setSocketError(QAbstractSocket::SslInternalError);
421             emit q->error(QAbstractSocket::SslInternalError);
422             return false;
423         }
424
425         if (configuration.privateKey.algorithm() == QSsl::Opaque) {
426             pkey = reinterpret_cast<EVP_PKEY *>(configuration.privateKey.handle());
427         } else {
428             // Load private key
429             pkey = q_EVP_PKEY_new();
430             // before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free.
431             // this lead to a memory leak. Now we use the *_set1_* functions which do not
432             // take ownership of the RSA/DSA key instance because the QSslKey already has ownership.
433             if (configuration.privateKey.algorithm() == QSsl::Rsa)
434                 q_EVP_PKEY_set1_RSA(pkey, reinterpret_cast<RSA *>(configuration.privateKey.handle()));
435             else
436                 q_EVP_PKEY_set1_DSA(pkey, reinterpret_cast<DSA *>(configuration.privateKey.handle()));
437         }
438
439         if (!q_SSL_CTX_use_PrivateKey(ctx, pkey)) {
440             q->setErrorString(QSslSocket::tr("Error loading private key, %1").arg(getErrorsFromOpenSsl()));
441             q->setSocketError(QAbstractSocket::SslInternalError);
442             emit q->error(QAbstractSocket::SslInternalError);
443             return false;
444         }
445         if (configuration.privateKey.algorithm() == QSsl::Opaque)
446             pkey = 0; // Don't free the private key, it belongs to QSslKey
447
448         // Check if the certificate matches the private key.
449         if (!q_SSL_CTX_check_private_key(ctx)) {
450             q->setErrorString(QSslSocket::tr("Private key does not certify public key, %1").arg(getErrorsFromOpenSsl()));
451             q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
452             emit q->error(QAbstractSocket::SslInvalidUserDataError);
453             return false;
454         }
455     }
456
457     // Initialize peer verification.
458     if (configuration.peerVerifyMode == QSslSocket::VerifyNone) {
459         q_SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
460     } else {
461         q_SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, q_X509Callback);
462     }
463
464     // Set verification depth.
465     if (configuration.peerVerifyDepth != 0)
466         q_SSL_CTX_set_verify_depth(ctx, configuration.peerVerifyDepth);
467
468     // Create and initialize SSL session
469     if (!(ssl = q_SSL_new(ctx))) {
470         // ### Bad error code
471         q->setErrorString(QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
472         q->setSocketError(QAbstractSocket::SslInternalError);
473         emit q->error(QAbstractSocket::SslInternalError);
474         return false;
475     }
476
477 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
478     if ((configuration.protocol == QSsl::TlsV1SslV3 ||
479         configuration.protocol == QSsl::TlsV1_0 ||
480         configuration.protocol == QSsl::SecureProtocols ||
481         configuration.protocol == QSsl::AnyProtocol) &&
482         client && q_SSLeay() >= 0x00090806fL) {
483         // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
484         QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
485         if (tlsHostName.isEmpty())
486             tlsHostName = hostName;
487         QByteArray ace = QUrl::toAce(tlsHostName);
488         // only send the SNI header if the URL is valid and not an IP
489         if (!ace.isEmpty()
490             && !QHostAddress().setAddress(tlsHostName)
491             && !(configuration.sslOptions & QSsl::SslOptionDisableServerNameIndication)) {
492             if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
493                 qWarning("could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
494         }
495     }
496 #endif
497
498     // Clear the session.
499     q_SSL_clear(ssl);
500     errorList.clear();
501
502     // Initialize memory BIOs for encryption and decryption.
503     readBio = q_BIO_new(q_BIO_s_mem());
504     writeBio = q_BIO_new(q_BIO_s_mem());
505     if (!readBio || !writeBio) {
506         q->setErrorString(QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
507         q->setSocketError(QAbstractSocket::SslInternalError);
508         emit q->error(QAbstractSocket::SslInternalError);
509         return false;
510     }
511
512     // Assign the bios.
513     q_SSL_set_bio(ssl, readBio, writeBio);
514
515     if (mode == QSslSocket::SslClientMode)
516         q_SSL_set_connect_state(ssl);
517     else
518         q_SSL_set_accept_state(ssl);
519
520     return true;
521 }
522
523 void QSslSocketBackendPrivate::destroySslContext()
524 {
525     if (ssl) {
526         q_SSL_free(ssl);
527         ssl = 0;
528     }
529     if (ctx) {
530         q_SSL_CTX_free(ctx);
531         ctx = 0;
532     }
533     if (pkey) {
534         q_EVP_PKEY_free(pkey);
535         pkey = 0;
536     }
537 }
538
539 /*!
540     \internal
541 */
542 void QSslSocketPrivate::deinitialize()
543 {
544     q_CRYPTO_set_id_callback(0);
545     q_CRYPTO_set_locking_callback(0);
546     q_ERR_free_strings();
547 }
548
549 /*!
550     \internal
551
552     Does the minimum amount of initialization to determine whether SSL
553     is supported or not.
554 */
555
556 bool QSslSocketPrivate::supportsSsl()
557 {
558     return ensureLibraryLoaded();
559 }
560
561 bool QSslSocketPrivate::ensureLibraryLoaded()
562 {
563     if (!q_resolveOpenSslSymbols())
564         return false;
565
566     // Check if the library itself needs to be initialized.
567     QMutexLocker locker(openssl_locks()->initLock());
568
569     if (!s_libraryLoaded) {
570         s_libraryLoaded = true;
571
572         // Initialize OpenSSL.
573         q_CRYPTO_set_id_callback(id_function);
574         q_CRYPTO_set_locking_callback(locking_function);
575         if (q_SSL_library_init() != 1)
576             return false;
577         q_SSL_load_error_strings();
578         q_OpenSSL_add_all_algorithms();
579
580         // Initialize OpenSSL's random seed.
581         if (!q_RAND_status()) {
582             struct {
583                 int msec;
584                 int sec;
585                 void *stack;
586             } randomish;
587
588             int attempts = 500;
589             do {
590                 if (attempts < 500) {
591 #ifdef Q_OS_UNIX
592                     struct timespec ts = {0, 33333333};
593                     nanosleep(&ts, 0);
594 #else
595                     Sleep(3);
596 #endif
597                     randomish.msec = attempts;
598                 }
599                 randomish.stack = (void *)&randomish;
600                 randomish.msec = QTime::currentTime().msec();
601                 randomish.sec = QTime::currentTime().second();
602                 q_RAND_seed((const char *)&randomish, sizeof(randomish));
603             } while (!q_RAND_status() && --attempts);
604             if (!attempts)
605                 return false;
606         }
607     }
608     return true;
609 }
610
611 void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
612 {
613     QMutexLocker locker(openssl_locks()->initLock());
614     if (s_loadedCiphersAndCerts)
615         return;
616     s_loadedCiphersAndCerts = true;
617
618     resetDefaultCiphers();
619
620     //load symbols needed to receive certificates from system store
621 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
622     QLibrary securityLib("/System/Library/Frameworks/Security.framework/Versions/Current/Security");
623     if (securityLib.load()) {
624         ptrSecCertificateGetData = (PtrSecCertificateGetData) securityLib.resolve("SecCertificateGetData");
625         if (!ptrSecCertificateGetData)
626             qWarning("could not resolve symbols in security library"); // should never happen
627
628         ptrSecTrustSettingsCopyCertificates = (PtrSecTrustSettingsCopyCertificates) securityLib.resolve("SecTrustSettingsCopyCertificates");
629         if (!ptrSecTrustSettingsCopyCertificates) { // method was introduced in Leopard, use legacy method if it's not there
630             ptrSecTrustCopyAnchorCertificates = (PtrSecTrustCopyAnchorCertificates) securityLib.resolve("SecTrustCopyAnchorCertificates");
631             if (!ptrSecTrustCopyAnchorCertificates)
632                 qWarning("could not resolve symbols in security library"); // should never happen
633         }
634     } else {
635         qWarning("could not load security library");
636     }
637 #elif defined(Q_OS_WIN)
638     HINSTANCE hLib = LoadLibraryW(L"Crypt32");
639     if (hLib) {
640 #if defined(Q_OS_WINCE)
641         ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, L"CertOpenStore");
642         ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, L"CertFindCertificateInStore");
643         ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, L"CertCloseStore");
644 #else
645         ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, "CertOpenSystemStoreW");
646         ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, "CertFindCertificateInStore");
647         ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, "CertCloseStore");
648 #endif
649         if (!ptrCertOpenSystemStoreW || !ptrCertFindCertificateInStore || !ptrCertCloseStore)
650             qWarning("could not resolve symbols in crypt32 library"); // should never happen
651     } else {
652         qWarning("could not load crypt32 library"); // should never happen
653     }
654 #elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
655     // check whether we can enable on-demand root-cert loading (i.e. check whether the sym links are there)
656     QList<QByteArray> dirs = unixRootCertDirectories();
657     QStringList symLinkFilter;
658     symLinkFilter << QLatin1String("[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].[0-9]");
659     for (int a = 0; a < dirs.count(); ++a) {
660         QDirIterator iterator(QLatin1String(dirs.at(a)), symLinkFilter, QDir::Files);
661         if (iterator.hasNext()) {
662             s_loadRootCertsOnDemand = true;
663             break;
664         }
665     }
666 #endif
667     // if on-demand loading was not enabled, load the certs now
668     if (!s_loadRootCertsOnDemand)
669         setDefaultCaCertificates(systemCaCertificates());
670 #ifdef Q_OS_WIN
671     //Enabled for fetching additional root certs from windows update on windows 6+
672     //This flag is set false by setDefaultCaCertificates() indicating the app uses
673     //its own cert bundle rather than the system one.
674     //Same logic that disables the unix on demand cert loading.
675     //Unlike unix, we do preload the certificates from the cert store.
676     if ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_6_0)
677         s_loadRootCertsOnDemand = true;
678 #endif
679 }
680
681 /*!
682     \internal
683
684     Declared static in QSslSocketPrivate, makes sure the SSL libraries have
685     been initialized.
686 */
687
688 void QSslSocketPrivate::ensureInitialized()
689 {
690     if (!supportsSsl())
691         return;
692
693     ensureCiphersAndCertsLoaded();
694 }
695
696 long QSslSocketPrivate::sslLibraryVersionNumber()
697 {
698     return q_SSLeay();
699 }
700
701 QString QSslSocketPrivate::sslLibraryVersionString()
702 {
703     if (!supportsSsl())
704         return QString();
705
706     const char *versionString = q_SSLeay_version(SSLEAY_VERSION);
707     if (!versionString)
708         return QString();
709
710     return QString::fromLatin1(versionString);
711 }
712
713 /*!
714     \internal
715
716     Declared static in QSslSocketPrivate, backend-dependent loading of
717     application-wide global ciphers.
718 */
719 void QSslSocketPrivate::resetDefaultCiphers()
720 {
721     SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
722     SSL *mySsl = q_SSL_new(myCtx);
723
724     QList<QSslCipher> ciphers;
725
726     STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(mySsl);
727     for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
728         if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
729             if (cipher->valid) {
730                 QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
731                 if (!ciph.isNull()) {
732                     if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
733                         ciphers << ciph;
734                 }
735             }
736         }
737     }
738
739     q_SSL_CTX_free(myCtx);
740     q_SSL_free(mySsl);
741
742     setDefaultSupportedCiphers(ciphers);
743     setDefaultCiphers(ciphers);
744 }
745
746 QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
747 {
748     ensureInitialized();
749 #ifdef QSSLSOCKET_DEBUG
750     QElapsedTimer timer;
751     timer.start();
752 #endif
753     QList<QSslCertificate> systemCerts;
754 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
755     CFArrayRef cfCerts;
756     OSStatus status = 1;
757
758     OSStatus SecCertificateGetData (
759        SecCertificateRef certificate,
760        CSSM_DATA_PTR data
761     );
762
763     if (ptrSecCertificateGetData) {
764         if (ptrSecTrustSettingsCopyCertificates)
765             status = ptrSecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &cfCerts);
766         else if (ptrSecTrustCopyAnchorCertificates)
767             status = ptrSecTrustCopyAnchorCertificates(&cfCerts);
768         if (!status) {
769             CFIndex size = CFArrayGetCount(cfCerts);
770             for (CFIndex i = 0; i < size; ++i) {
771                 SecCertificateRef cfCert = (SecCertificateRef)CFArrayGetValueAtIndex(cfCerts, i);
772                 CSSM_DATA data;
773                 CSSM_DATA_PTR dataPtr = &data;
774                 if (ptrSecCertificateGetData(cfCert, dataPtr)) {
775                     qWarning("error retrieving a CA certificate from the system store");
776                 } else {
777                     int len = data.Length;
778                     char *rawData = reinterpret_cast<char *>(data.Data);
779                     QByteArray rawCert(rawData, len);
780                     systemCerts.append(QSslCertificate::fromData(rawCert, QSsl::Der));
781                 }
782             }
783             CFRelease(cfCerts);
784         }
785         else {
786            // no detailed error handling here
787            qWarning("could not retrieve system CA certificates");
788         }
789     }
790 #elif defined(Q_OS_WIN)
791     if (ptrCertOpenSystemStoreW && ptrCertFindCertificateInStore && ptrCertCloseStore) {
792         HCERTSTORE hSystemStore;
793 #if defined(Q_OS_WINCE)
794         hSystemStore = ptrCertOpenSystemStoreW(CERT_STORE_PROV_SYSTEM_W,
795                                                0,
796                                                0,
797                                                CERT_STORE_NO_CRYPT_RELEASE_FLAG|CERT_SYSTEM_STORE_CURRENT_USER,
798                                                L"ROOT");
799 #else
800         hSystemStore = ptrCertOpenSystemStoreW(0, L"ROOT");
801 #endif
802         if(hSystemStore) {
803             PCCERT_CONTEXT pc = NULL;
804             while(1) {
805                 pc = ptrCertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc);
806                 if(!pc)
807                     break;
808                 QByteArray der((const char *)(pc->pbCertEncoded), static_cast<int>(pc->cbCertEncoded));
809                 QSslCertificate cert(der, QSsl::Der);
810                 systemCerts.append(cert);
811             }
812             ptrCertCloseStore(hSystemStore, 0);
813         }
814     }
815 #elif defined(Q_OS_UNIX)
816     QSet<QString> certFiles;
817     QList<QByteArray> directories = unixRootCertDirectories();
818     QDir currentDir;
819     QStringList nameFilters;
820     nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
821     currentDir.setNameFilters(nameFilters);
822     for (int a = 0; a < directories.count(); a++) {
823         currentDir.setPath(QLatin1String(directories.at(a)));
824         QDirIterator it(currentDir);
825         while(it.hasNext()) {
826             it.next();
827             // use canonical path here to not load the same certificate twice if symlinked
828             certFiles.insert(it.fileInfo().canonicalFilePath());
829         }
830     }
831     QSetIterator<QString> it(certFiles);
832     while(it.hasNext()) {
833         systemCerts.append(QSslCertificate::fromPath(it.next()));
834     }
835     systemCerts.append(QSslCertificate::fromPath(QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem)); // Fedora, Mandriva
836     systemCerts.append(QSslCertificate::fromPath(QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), QSsl::Pem)); // FreeBSD's ca_root_nss
837 #endif
838 #ifdef QSSLSOCKET_DEBUG
839     qDebug() << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
840     qDebug() << "imported " << systemCerts.count() << " certificates";
841 #endif
842
843     return systemCerts;
844 }
845
846 void QSslSocketBackendPrivate::startClientEncryption()
847 {
848     Q_Q(QSslSocket);
849     if (!initSslContext()) {
850         q->setErrorString(QSslSocket::tr("Unable to init Ssl Context: %1").arg(getErrorsFromOpenSsl()));
851         q->setSocketError(QAbstractSocket::SslInternalError);
852         emit q->error(QAbstractSocket::SslInternalError);
853         return;
854     }
855
856     // Start connecting. This will place outgoing data in the BIO, so we
857     // follow up with calling transmit().
858     startHandshake();
859     transmit();
860 }
861
862 void QSslSocketBackendPrivate::startServerEncryption()
863 {
864     Q_Q(QSslSocket);
865     if (!initSslContext()) {
866         q->setErrorString(QSslSocket::tr("Unable to init Ssl Context: %1").arg(getErrorsFromOpenSsl()));
867         q->setSocketError(QAbstractSocket::SslInternalError);
868         emit q->error(QAbstractSocket::SslInternalError);
869         return;
870     }
871
872     // Start connecting. This will place outgoing data in the BIO, so we
873     // follow up with calling transmit().
874     startHandshake();
875     transmit();
876 }
877
878 /*!
879     \internal
880
881     Transmits encrypted data between the BIOs and the socket.
882 */
883 void QSslSocketBackendPrivate::transmit()
884 {
885     Q_Q(QSslSocket);
886
887     // If we don't have any SSL context, don't bother transmitting.
888     if (!ssl)
889         return;
890
891     bool transmitting;
892     do {
893         transmitting = false;
894
895         // If the connection is secure, we can transfer data from the write
896         // buffer (in plain text) to the write BIO through SSL_write.
897         if (connectionEncrypted && !writeBuffer.isEmpty()) {
898             qint64 totalBytesWritten = 0;
899             int nextDataBlockSize;
900             while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
901                 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
902                 if (writtenBytes <= 0) {
903                     // ### Better error handling.
904                     q->setErrorString(QSslSocket::tr("Unable to write data: %1").arg(getErrorsFromOpenSsl()));
905                     q->setSocketError(QAbstractSocket::SslInternalError);
906                     emit q->error(QAbstractSocket::SslInternalError);
907                     return;
908                 }
909 #ifdef QSSLSOCKET_DEBUG
910                 qDebug() << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
911 #endif
912                 writeBuffer.free(writtenBytes);
913                 totalBytesWritten += writtenBytes;
914
915                 if (writtenBytes < nextDataBlockSize) {
916                     // break out of the writing loop and try again after we had read
917                     transmitting = true;
918                     break;
919                 }
920             }
921
922             if (totalBytesWritten > 0) {
923                 // Don't emit bytesWritten() recursively.
924                 if (!emittedBytesWritten) {
925                     emittedBytesWritten = true;
926                     emit q->bytesWritten(totalBytesWritten);
927                     emittedBytesWritten = false;
928                 }
929             }
930         }
931
932         // Check if we've got any data to be written to the socket.
933         QVarLengthArray<char, 4096> data;
934         int pendingBytes;
935         while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0) {
936             // Read encrypted data from the write BIO into a buffer.
937             data.resize(pendingBytes);
938             int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
939
940             // Write encrypted data from the buffer to the socket.
941             qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
942 #ifdef QSSLSOCKET_DEBUG
943             qDebug() << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket" << actualWritten << "actual.";
944 #endif
945             if (actualWritten < 0) {
946                 //plain socket write fails if it was in the pending close state.
947                 q->setErrorString(plainSocket->errorString());
948                 q->setSocketError(plainSocket->error());
949                 emit q->error(plainSocket->error());
950                 return;
951             }
952             transmitting = true;
953         }
954
955         // Check if we've got any data to be read from the socket.
956         if (!connectionEncrypted || !readBufferMaxSize || readBuffer.size() < readBufferMaxSize)
957             while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
958                 // Read encrypted data from the socket into a buffer.
959                 data.resize(pendingBytes);
960                 // just peek() here because q_BIO_write could write less data than expected
961                 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
962 #ifdef QSSLSOCKET_DEBUG
963                 qDebug() << "QSslSocketBackendPrivate::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
964 #endif
965                 // Write encrypted data from the buffer into the read BIO.
966                 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
967
968                 // do the actual read() here and throw away the results.
969                 if (writtenToBio > 0) {
970                     // ### TODO: make this cheaper by not making it memcpy. E.g. make it work with data=0x0 or make it work with seek
971                     plainSocket->read(data.data(), writtenToBio);
972                 } else {
973                     // ### Better error handling.
974                     q->setErrorString(QSslSocket::tr("Unable to decrypt data: %1").arg(getErrorsFromOpenSsl()));
975                     q->setSocketError(QAbstractSocket::SslInternalError);
976                     emit q->error(QAbstractSocket::SslInternalError);
977                     return;
978                 }
979
980                 transmitting = true;
981             }
982
983         // If the connection isn't secured yet, this is the time to retry the
984         // connect / accept.
985         if (!connectionEncrypted) {
986 #ifdef QSSLSOCKET_DEBUG
987             qDebug() << "QSslSocketBackendPrivate::transmit: testing encryption";
988 #endif
989             if (startHandshake()) {
990 #ifdef QSSLSOCKET_DEBUG
991                 qDebug() << "QSslSocketBackendPrivate::transmit: encryption established";
992 #endif
993                 connectionEncrypted = true;
994                 transmitting = true;
995             } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
996 #ifdef QSSLSOCKET_DEBUG
997                 qDebug() << "QSslSocketBackendPrivate::transmit: connection lost";
998 #endif
999                 break;
1000             } else if (paused) {
1001                 // just wait until the user continues
1002                 return;
1003             } else {
1004 #ifdef QSSLSOCKET_DEBUG
1005                 qDebug() << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1006 #endif
1007             }
1008         }
1009
1010         // If the request is small and the remote host closes the transmission
1011         // after sending, there's a chance that startHandshake() will already
1012         // have triggered a shutdown.
1013         if (!ssl)
1014             continue;
1015
1016         // We always read everything from the SSL decryption buffers, even if
1017         // we have a readBufferMaxSize. There's no point in leaving data there
1018         // just so that readBuffer.size() == readBufferMaxSize.
1019         int readBytes = 0;
1020         data.resize(4096);
1021         ::memset(data.data(), 0, data.size());
1022         do {
1023             // Don't use SSL_pending(). It's very unreliable.
1024             if ((readBytes = q_SSL_read(ssl, data.data(), data.size())) > 0) {
1025 #ifdef QSSLSOCKET_DEBUG
1026                 qDebug() << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1027 #endif
1028                 char *ptr = readBuffer.reserve(readBytes);
1029                 ::memcpy(ptr, data.data(), readBytes);
1030
1031                 if (readyReadEmittedPointer)
1032                     *readyReadEmittedPointer = true;
1033                 emit q->readyRead();
1034                 transmitting = true;
1035                 continue;
1036             }
1037
1038             // Error.
1039             switch (q_SSL_get_error(ssl, readBytes)) {
1040             case SSL_ERROR_WANT_READ:
1041             case SSL_ERROR_WANT_WRITE:
1042                 // Out of data.
1043                 break;
1044             case SSL_ERROR_ZERO_RETURN:
1045                 // The remote host closed the connection.
1046 #ifdef QSSLSOCKET_DEBUG
1047                 qDebug() << "QSslSocketBackendPrivate::transmit: remote disconnect";
1048 #endif
1049                 plainSocket->disconnectFromHost();
1050                 break;
1051             case SSL_ERROR_SYSCALL: // some IO error
1052             case SSL_ERROR_SSL: // error in the SSL library
1053                 // we do not know exactly what the error is, nor whether we can recover from it,
1054                 // so just return to prevent an endless loop in the outer "while" statement
1055                 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1056                 q->setSocketError(QAbstractSocket::SslInternalError);
1057                 emit q->error(QAbstractSocket::SslInternalError);
1058                 return;
1059             default:
1060                 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1061                 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1062                 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1063                 // SSL_CTX_set_client_cert_cb(), which we do not call.
1064                 // So this default case should never be triggered.
1065                 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1066                 q->setSocketError(QAbstractSocket::SslInternalError);
1067                 emit q->error(QAbstractSocket::SslInternalError);
1068                 break;
1069             }
1070         } while (ssl && readBytes > 0);
1071     } while (ssl && ctx && transmitting);
1072 }
1073
1074 static QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1075 {
1076     QSslError error;
1077     switch (errorCode) {
1078     case X509_V_OK:
1079         // X509_V_OK is also reported if the peer had no certificate.
1080         break;
1081     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1082         error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1083     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1084         error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1085     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1086         error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1087     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1088         error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1089     case X509_V_ERR_CERT_NOT_YET_VALID:
1090         error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1091     case X509_V_ERR_CERT_HAS_EXPIRED:
1092         error = QSslError(QSslError::CertificateExpired, cert); break;
1093     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1094         error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1095     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1096         error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1097     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1098         error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1099     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1100         error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1101     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1102         error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1103     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1104         error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1105     case X509_V_ERR_CERT_REVOKED:
1106         error = QSslError(QSslError::CertificateRevoked, cert); break;
1107     case X509_V_ERR_INVALID_CA:
1108         error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1109     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1110         error = QSslError(QSslError::PathLengthExceeded, cert); break;
1111     case X509_V_ERR_INVALID_PURPOSE:
1112         error = QSslError(QSslError::InvalidPurpose, cert); break;
1113     case X509_V_ERR_CERT_UNTRUSTED:
1114         error = QSslError(QSslError::CertificateUntrusted, cert); break;
1115     case X509_V_ERR_CERT_REJECTED:
1116         error = QSslError(QSslError::CertificateRejected, cert); break;
1117     default:
1118         error = QSslError(QSslError::UnspecifiedError, cert); break;
1119     }
1120     return error;
1121 }
1122
1123 bool QSslSocketBackendPrivate::startHandshake()
1124 {
1125     Q_Q(QSslSocket);
1126
1127     // Check if the connection has been established. Get all errors from the
1128     // verification stage.
1129     _q_sslErrorList()->mutex.lock();
1130     _q_sslErrorList()->errors.clear();
1131     int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
1132
1133     const QList<QPair<int, int> > &lastErrors = _q_sslErrorList()->errors;
1134     for (int i = 0; i < lastErrors.size(); ++i) {
1135         const QPair<int, int> &currentError = lastErrors.at(i);
1136         // Initialize the peer certificate chain in order to find which certificate caused this error
1137         if (configuration.peerCertificateChain.isEmpty())
1138             configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1139         emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.first,
1140                                 configuration.peerCertificateChain.value(currentError.second)));
1141         if (q->state() != QAbstractSocket::ConnectedState)
1142             break;
1143     }
1144
1145     errorList << lastErrors;
1146     _q_sslErrorList()->mutex.unlock();
1147
1148     // Connection aborted during handshake phase.
1149     if (q->state() != QAbstractSocket::ConnectedState)
1150         return false;
1151
1152     // Check if we're encrypted or not.
1153     if (result <= 0) {
1154         switch (q_SSL_get_error(ssl, result)) {
1155         case SSL_ERROR_WANT_READ:
1156         case SSL_ERROR_WANT_WRITE:
1157             // The handshake is not yet complete.
1158             break;
1159         default:
1160             q->setErrorString(QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl()));
1161             q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1162 #ifdef QSSLSOCKET_DEBUG
1163             qDebug() << "QSslSocketBackendPrivate::startHandshake: error!" << q->errorString();
1164 #endif
1165             emit q->error(QAbstractSocket::SslHandshakeFailedError);
1166             q->abort();
1167         }
1168         return false;
1169     }
1170
1171     // Store the peer certificate and chain. For clients, the peer certificate
1172     // chain includes the peer certificate; for servers, it doesn't. Both the
1173     // peer certificate and the chain may be empty if the peer didn't present
1174     // any certificate.
1175     if (configuration.peerCertificateChain.isEmpty())
1176         configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1177     X509 *x509 = q_SSL_get_peer_certificate(ssl);
1178     configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1179     q_X509_free(x509);
1180
1181     // Start translating errors.
1182     QList<QSslError> errors;
1183
1184     // check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
1185     foreach (const QSslCertificate &cert, configuration.peerCertificateChain) {
1186         if (QSslCertificatePrivate::isBlacklisted(cert)) {
1187             QSslError error(QSslError::CertificateBlacklisted, cert);
1188             errors << error;
1189             emit q->peerVerifyError(error);
1190             if (q->state() != QAbstractSocket::ConnectedState)
1191                 return false;
1192         }
1193     }
1194
1195     bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1196                         || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1197                             && mode == QSslSocket::SslClientMode);
1198
1199     // Check the peer certificate itself. First try the subject's common name
1200     // (CN) as a wildcard, then try all alternate subject name DNS entries the
1201     // same way.
1202     if (!configuration.peerCertificate.isNull()) {
1203         // but only if we're a client connecting to a server
1204         // if we're the server, don't check CN
1205         if (mode == QSslSocket::SslClientMode) {
1206             QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1207
1208             if (!isMatchingHostname(configuration.peerCertificate, peerName)) {
1209                 // No matches in common names or alternate names.
1210                 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1211                 errors << error;
1212                 emit q->peerVerifyError(error);
1213                 if (q->state() != QAbstractSocket::ConnectedState)
1214                     return false;
1215             }
1216         }
1217     } else {
1218         // No peer certificate presented. Report as error if the socket
1219         // expected one.
1220         if (doVerifyPeer) {
1221             QSslError error(QSslError::NoPeerCertificate);
1222             errors << error;
1223             emit q->peerVerifyError(error);
1224             if (q->state() != QAbstractSocket::ConnectedState)
1225                 return false;
1226         }
1227     }
1228
1229     // Translate errors from the error list into QSslErrors.
1230     for (int i = 0; i < errorList.size(); ++i) {
1231         const QPair<int, int> &errorAndDepth = errorList.at(i);
1232         int err = errorAndDepth.first;
1233         int depth = errorAndDepth.second;
1234         errors << _q_OpenSSL_to_QSslError(err, configuration.peerCertificateChain.value(depth));
1235     }
1236
1237     if (!errors.isEmpty()) {
1238         sslErrors = errors;
1239
1240 #ifdef Q_OS_WIN
1241         //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
1242         if (doVerifyPeer
1243             && s_loadRootCertsOnDemand
1244             && allowRootCertOnDemandLoading
1245             && !verifyErrorsHaveBeenIgnored()) {
1246             //Windows desktop versions starting from vista ship with minimal set of roots
1247             //and download on demand from the windows update server CA roots that are
1248             //trusted by MS.
1249             //However, this is only transparent if using WinINET - we have to trigger it
1250             //ourselves.
1251             QSslCertificate certToFetch;
1252             bool fetchCertificate = true;
1253             for (int i=0; i< sslErrors.count(); i++) {
1254                 switch (sslErrors.at(i).error()) {
1255                 case QSslError::UnableToGetLocalIssuerCertificate: // site presented intermediate cert, but root is unknown
1256                 case QSslError::SelfSignedCertificateInChain: // site presented a complete chain, but root is unknown
1257                     certToFetch = sslErrors.at(i).certificate();
1258                     break;
1259                 case QSslError::SelfSignedCertificate:
1260                 case QSslError::CertificateBlacklisted:
1261                     //With these errors, we know it will be untrusted so save time by not asking windows
1262                     fetchCertificate = false;
1263                     break;
1264                 default:
1265 #ifdef QSSLSOCKET_DEBUG
1266                     qDebug() << sslErrors.at(i).errorString();
1267 #endif
1268                     break;
1269                 }
1270             }
1271             if (fetchCertificate && !certToFetch.isNull()) {
1272                 fetchCaRootForCert(certToFetch);
1273                 return false;
1274             }
1275         }
1276 #endif
1277
1278         if (!checkSslErrors())
1279             return false;
1280     } else {
1281         sslErrors.clear();
1282     }
1283
1284     continueHandshake();
1285     return true;
1286 }
1287
1288 bool QSslSocketBackendPrivate::checkSslErrors()
1289 {
1290     Q_Q(QSslSocket);
1291     if (sslErrors.isEmpty())
1292         return true;
1293
1294     emit q->sslErrors(sslErrors);
1295
1296     bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1297                         || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1298                             && mode == QSslSocket::SslClientMode);
1299     bool doEmitSslError = !verifyErrorsHaveBeenIgnored();
1300     // check whether we need to emit an SSL handshake error
1301     if (doVerifyPeer && doEmitSslError) {
1302         if (q->pauseMode() & QAbstractSocket::PauseOnNotify) {
1303             pauseSocketNotifiers(q);
1304             paused = true;
1305         } else {
1306             q->setErrorString(sslErrors.first().errorString());
1307             q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1308             emit q->error(QAbstractSocket::SslHandshakeFailedError);
1309             plainSocket->disconnectFromHost();
1310         }
1311         return false;
1312     }
1313     return true;
1314 }
1315
1316 #ifdef Q_OS_WIN
1317
1318 void QSslSocketBackendPrivate::fetchCaRootForCert(const QSslCertificate &cert)
1319 {
1320     Q_Q(QSslSocket);
1321     //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1322     //so the request is done in a worker thread.
1323     QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, mode);
1324     QObject::connect(fetcher, SIGNAL(finished(QSslCertificate,QSslCertificate)), q, SLOT(_q_caRootLoaded(QSslCertificate,QSslCertificate)), Qt::QueuedConnection);
1325     QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1326     pauseSocketNotifiers(q);
1327     paused = true;
1328 }
1329
1330 //This is the callback from QWindowsCaRootFetcher, trustedRoot will be invalid (default constructed) if it failed.
1331 void QSslSocketBackendPrivate::_q_caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1332 {
1333     Q_Q(QSslSocket);
1334     if (trustedRoot.isValid()) {
1335         if (s_loadRootCertsOnDemand) {
1336             //Add the new root cert to default cert list for use by future sockets
1337             QSslSocket::addDefaultCaCertificate(trustedRoot);
1338         }
1339         //Add the new root cert to this socket for future connections
1340         q->addCaCertificate(trustedRoot);
1341         //Remove the broken chain ssl errors (as chain is verified by windows)
1342         for (int i=sslErrors.count() - 1; i >= 0; --i) {
1343             if (sslErrors.at(i).certificate() == cert) {
1344                 switch (sslErrors.at(i).error()) {
1345                 case QSslError::UnableToGetLocalIssuerCertificate:
1346                 case QSslError::CertificateUntrusted:
1347                 case QSslError::UnableToVerifyFirstCertificate:
1348                 case QSslError::SelfSignedCertificateInChain:
1349                     // error can be ignored if OS says the chain is trusted
1350                     sslErrors.removeAt(i);
1351                     break;
1352                 default:
1353                     // error cannot be ignored
1354                     break;
1355                 }
1356             }
1357         }
1358     }
1359     // Continue with remaining errors
1360     if (plainSocket)
1361         plainSocket->resume();
1362     paused = false;
1363     if (checkSslErrors())
1364         continueHandshake();
1365 }
1366
1367 class QWindowsCaRootFetcherThread : public QThread
1368 {
1369 public:
1370     QWindowsCaRootFetcherThread()
1371     {
1372         qRegisterMetaType<QSslCertificate>();
1373         setObjectName(QStringLiteral("QWindowsCaRootFetcher"));
1374         start();
1375     }
1376     ~QWindowsCaRootFetcherThread()
1377     {
1378         quit();
1379         wait(15500); // worst case, a running request can block for 15 seconds
1380     }
1381 };
1382
1383 Q_GLOBAL_STATIC(QWindowsCaRootFetcherThread, windowsCaRootFetcherThread);
1384
1385 QWindowsCaRootFetcher::QWindowsCaRootFetcher(const QSslCertificate &certificate, QSslSocket::SslMode sslMode)
1386     : cert(certificate), mode(sslMode)
1387 {
1388     moveToThread(windowsCaRootFetcherThread());
1389 }
1390
1391 QWindowsCaRootFetcher::~QWindowsCaRootFetcher()
1392 {
1393 }
1394
1395 void QWindowsCaRootFetcher::start()
1396 {
1397     QByteArray der = cert.toDer();
1398     PCCERT_CONTEXT wincert = CertCreateCertificateContext(X509_ASN_ENCODING, (const BYTE *)der.constData(), der.length());
1399     if (!wincert) {
1400 #ifdef QSSLSOCKET_DEBUG
1401         qDebug("QWindowsCaRootFetcher failed to convert certificate to windows form");
1402 #endif
1403         emit finished(cert, QSslCertificate());
1404         deleteLater();
1405         return;
1406     }
1407
1408     CERT_CHAIN_PARA parameters;
1409     memset(&parameters, 0, sizeof(parameters));
1410     parameters.cbSize = sizeof(parameters);
1411     // set key usage constraint
1412     parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
1413     parameters.RequestedUsage.Usage.cUsageIdentifier = 1;
1414     LPSTR oid = (LPSTR)(mode == QSslSocket::SslClientMode ? szOID_PKIX_KP_SERVER_AUTH : szOID_PKIX_KP_CLIENT_AUTH);
1415     parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &oid;
1416
1417 #ifdef QSSLSOCKET_DEBUG
1418     QElapsedTimer stopwatch;
1419     stopwatch.start();
1420 #endif
1421     PCCERT_CHAIN_CONTEXT chain;
1422     BOOL result = CertGetCertificateChain(
1423         0, //default engine
1424         wincert,
1425         0, //current date/time
1426         0, //default store
1427         &parameters,
1428         0, //default dwFlags
1429         0, //reserved
1430         &chain);
1431 #ifdef QSSLSOCKET_DEBUG
1432     qDebug() << "QWindowsCaRootFetcher" << stopwatch.elapsed() << "ms to get chain";
1433 #endif
1434
1435     QSslCertificate trustedRoot;
1436     if (result) {
1437 #ifdef QSSLSOCKET_DEBUG
1438         qDebug() << "QWindowsCaRootFetcher - examining windows chains";
1439         if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1440             qDebug() << " - TRUSTED";
1441         else
1442             qDebug() << " - NOT TRUSTED" << chain->TrustStatus.dwErrorStatus;
1443         if (chain->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED)
1444             qDebug() << " - SELF SIGNED";
1445         qDebug() << "QSslSocketBackendPrivate::fetchCaRootForCert - dumping simple chains";
1446         for (unsigned int i = 0; i < chain->cChain; i++) {
1447             if (chain->rgpChain[i]->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1448                 qDebug() << " - TRUSTED SIMPLE CHAIN" << i;
1449             else
1450                 qDebug() << " - UNTRUSTED SIMPLE CHAIN" << i << "reason:" << chain->rgpChain[i]->TrustStatus.dwErrorStatus;
1451             for (unsigned int j = 0; j < chain->rgpChain[i]->cElement; j++) {
1452                 QSslCertificate foundCert(QByteArray((const char *)chain->rgpChain[i]->rgpElement[j]->pCertContext->pbCertEncoded
1453                     , chain->rgpChain[i]->rgpElement[j]->pCertContext->cbCertEncoded), QSsl::Der);
1454                 qDebug() << "   - " << foundCert;
1455             }
1456         }
1457         qDebug() << " - and" << chain->cLowerQualityChainContext << "low quality chains"; //expect 0, we haven't asked for them
1458 #endif
1459
1460         //based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa377182%28v=vs.85%29.aspx
1461         //about the final chain rgpChain[cChain-1] which must begin with a trusted root to be valid
1462         if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1463             && chain->cChain > 0) {
1464             const PCERT_SIMPLE_CHAIN finalChain = chain->rgpChain[chain->cChain - 1];
1465             // http://msdn.microsoft.com/en-us/library/windows/desktop/aa377544%28v=vs.85%29.aspx
1466             // rgpElement[0] is the end certificate chain element. rgpElement[cElement-1] is the self-signed "root" certificate element.
1467             if (finalChain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1468                 && finalChain->cElement > 0) {
1469                     trustedRoot = QSslCertificate(QByteArray((const char *)finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->pbCertEncoded
1470                         , finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->cbCertEncoded), QSsl::Der);
1471             }
1472         }
1473         CertFreeCertificateChain(chain);
1474     }
1475     CertFreeCertificateContext(wincert);
1476
1477     emit finished(cert, trustedRoot);
1478     deleteLater();
1479 }
1480 #endif
1481
1482 void QSslSocketBackendPrivate::disconnectFromHost()
1483 {
1484     if (ssl) {
1485         q_SSL_shutdown(ssl);
1486         transmit();
1487     }
1488     plainSocket->disconnectFromHost();
1489 }
1490
1491 void QSslSocketBackendPrivate::disconnected()
1492 {
1493     if (plainSocket->bytesAvailable() <= 0)
1494         destroySslContext();
1495     //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1496     //it will be destroyed when the socket is deleted.
1497 }
1498
1499 QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1500 {
1501     if (!ssl || !ctx)
1502         return QSslCipher();
1503 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1504     // FIXME This is fairly evil, but needed to keep source level compatibility
1505     // with the OpenSSL 0.9.x implementation at maximum -- some other functions
1506     // don't take a const SSL_CIPHER* when they should
1507     SSL_CIPHER *sessionCipher = const_cast<SSL_CIPHER *>(q_SSL_get_current_cipher(ssl));
1508 #else
1509     SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1510 #endif
1511     return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1512 }
1513
1514 void QSslSocketBackendPrivate::continueHandshake()
1515 {
1516     Q_Q(QSslSocket);
1517     // if we have a max read buffer size, reset the plain socket's to match
1518     if (readBufferMaxSize)
1519         plainSocket->setReadBufferSize(readBufferMaxSize);
1520
1521     connectionEncrypted = true;
1522     emit q->encrypted();
1523     if (autoStartHandshake && pendingClose) {
1524         pendingClose = false;
1525         q->disconnectFromHost();
1526     }
1527 }
1528
1529 QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1530 {
1531     ensureInitialized();
1532     QList<QSslCertificate> certificates;
1533     for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1534         if (X509 *entry = q_sk_X509_value(x509, i))
1535             certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1536     }
1537     return certificates;
1538 }
1539
1540 QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1541 {
1542     QString errorString;
1543     unsigned long errNum;
1544     while((errNum = q_ERR_get_error())) {
1545         if (! errorString.isEmpty())
1546             errorString.append(QLatin1String(", "));
1547         const char *error = q_ERR_error_string(errNum, NULL);
1548         errorString.append(QString::fromAscii(error)); // error is ascii according to man ERR_error_string
1549     }
1550     return errorString;
1551 }
1552
1553 bool QSslSocketBackendPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
1554 {
1555     QStringList commonNameList = cert.subjectInfo(QSslCertificate::CommonName);
1556
1557     foreach (const QString &commonName, commonNameList) {
1558         if (isMatchingHostname(commonName.toLower(), peerName.toLower())) {
1559             return true;
1560         }
1561     }
1562
1563     foreach (const QString &altName, cert.subjectAlternativeNames().values(QSsl::DnsEntry)) {
1564         if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
1565             return true;
1566         }
1567     }
1568
1569     return false;
1570 }
1571
1572 bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1573 {
1574     int wildcard = cn.indexOf(QLatin1Char('*'));
1575
1576     // Check this is a wildcard cert, if not then just compare the strings
1577     if (wildcard < 0)
1578         return cn == hostname;
1579
1580     int firstCnDot = cn.indexOf(QLatin1Char('.'));
1581     int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1582
1583     // Check at least 3 components
1584     if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1585         return false;
1586
1587     // Check * is last character of 1st component (ie. there's a following .)
1588     if (wildcard+1 != firstCnDot)
1589         return false;
1590
1591     // Check only one star
1592     if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1593         return false;
1594
1595     // Check characters preceding * (if any) match
1596     if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1597         return false;
1598
1599     // Check characters following first . match
1600     if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1601         return false;
1602
1603     // Check if the hostname is an IP address, if so then wildcards are not allowed
1604     QHostAddress addr(hostname);
1605     if (!addr.isNull())
1606         return false;
1607
1608     // Ok, I guess this was a wildcard CN and the hostname matches.
1609     return true;
1610 }
1611
1612 QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certificateChain, const QString &hostName)
1613 {
1614     QList<QSslError> errors;
1615     if (certificateChain.count() <= 0) {
1616         errors << QSslError(QSslError::UnspecifiedError);
1617         return errors;
1618     }
1619
1620     // Setup the store with the default CA certificates
1621     X509_STORE *certStore = q_X509_STORE_new();
1622     if (!certStore) {
1623         qWarning() << "Unable to create certificate store";
1624         errors << QSslError(QSslError::UnspecifiedError);
1625         return errors;
1626     }
1627
1628     if (s_loadRootCertsOnDemand) {
1629         setDefaultCaCertificates(defaultCaCertificates() + systemCaCertificates());
1630     }
1631
1632     QList<QSslCertificate> expiredCerts;
1633
1634     foreach (const QSslCertificate &caCertificate, QSslSocket::defaultCaCertificates()) {
1635         // add expired certs later, so that the
1636         // valid ones are used before the expired ones
1637         if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
1638             expiredCerts.append(caCertificate);
1639         } else {
1640             q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1641         }
1642     }
1643
1644     bool addExpiredCerts = true;
1645 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
1646     //On Leopard SSL does not work if we add the expired certificates.
1647     if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
1648         addExpiredCerts = false;
1649 #endif
1650     // now add the expired certs
1651     if (addExpiredCerts) {
1652         foreach (const QSslCertificate &caCertificate, expiredCerts) {
1653             q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1654         }
1655     }
1656
1657     QMutexLocker sslErrorListMutexLocker(&_q_sslErrorList()->mutex);
1658
1659     // Register a custom callback to get all verification errors.
1660     X509_STORE_set_verify_cb_func(certStore, q_X509Callback);
1661
1662     // Build the chain of intermediate certificates
1663     STACK_OF(X509) *intermediates = 0;
1664     if (certificateChain.length() > 1) {
1665         intermediates = (STACK_OF(X509) *) q_sk_new_null();
1666
1667         if (!intermediates) {
1668             q_X509_STORE_free(certStore);
1669             errors << QSslError(QSslError::UnspecifiedError);
1670             return errors;
1671         }
1672
1673         bool first = true;
1674         foreach (const QSslCertificate &cert, certificateChain) {
1675             if (first) {
1676                 first = false;
1677                 continue;
1678             }
1679 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1680             q_sk_push( (_STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1681 #else
1682             q_sk_push( (STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1683 #endif
1684         }
1685     }
1686
1687     X509_STORE_CTX *storeContext = q_X509_STORE_CTX_new();
1688     if (!storeContext) {
1689         q_X509_STORE_free(certStore);
1690         errors << QSslError(QSslError::UnspecifiedError);
1691         return errors;
1692     }
1693
1694     if (!q_X509_STORE_CTX_init(storeContext, certStore, reinterpret_cast<X509 *>(certificateChain[0].handle()), intermediates)) {
1695         q_X509_STORE_CTX_free(storeContext);
1696         q_X509_STORE_free(certStore);
1697         errors << QSslError(QSslError::UnspecifiedError);
1698         return errors;
1699     }
1700
1701     // Now we can actually perform the verification of the chain we have built.
1702     // We ignore the result of this function since we process errors via the
1703     // callback.
1704     (void) q_X509_verify_cert(storeContext);
1705
1706     q_X509_STORE_CTX_free(storeContext);
1707 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1708     q_sk_free( (_STACK *) intermediates);
1709 #else
1710     q_sk_free( (STACK *) intermediates);
1711 #endif
1712
1713     // Now process the errors
1714     const QList<QPair<int, int> > errorList = _q_sslErrorList()->errors;
1715     _q_sslErrorList()->errors.clear();
1716
1717     sslErrorListMutexLocker.unlock();
1718
1719     // Translate the errors
1720     if (QSslCertificatePrivate::isBlacklisted(certificateChain[0])) {
1721         QSslError error(QSslError::CertificateBlacklisted, certificateChain[0]);
1722         errors << error;
1723     }
1724
1725     // Check the certificate name against the hostname if one was specified
1726     if ((!hostName.isEmpty()) && (!isMatchingHostname(certificateChain[0], hostName))) {
1727         // No matches in common names or alternate names.
1728         QSslError error(QSslError::HostNameMismatch, certificateChain[0]);
1729         errors << error;
1730     }
1731
1732     // Translate errors from the error list into QSslErrors.
1733     for (int i = 0; i < errorList.size(); ++i) {
1734         const QPair<int, int> &errorAndDepth = errorList.at(i);
1735         int err = errorAndDepth.first;
1736         int depth = errorAndDepth.second;
1737         errors << _q_OpenSSL_to_QSslError(err, certificateChain.value(depth));
1738     }
1739
1740     q_X509_STORE_free(certStore);
1741
1742     return errors;
1743 }
1744
1745 QT_END_NAMESPACE