59f6f53fef4f3e5b18835bc9ea98d1882ea2766b
[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:
1256                     certToFetch = sslErrors.at(i).certificate();
1257                     break;
1258                 case QSslError::SelfSignedCertificate:
1259                 case QSslError::CertificateBlacklisted:
1260                     //With these errors, we know it will be untrusted so save time by not asking windows
1261                     fetchCertificate = false;
1262                     break;
1263                 default:
1264 #ifdef QSSLSOCKET_DEBUG
1265                     qDebug() << sslErrors.at(i).errorString();
1266 #endif
1267                     break;
1268                 }
1269             }
1270             if (fetchCertificate && !certToFetch.isNull()) {
1271                 fetchCaRootForCert(certToFetch);
1272                 return false;
1273             }
1274         }
1275 #endif
1276
1277         if (!checkSslErrors())
1278             return false;
1279     } else {
1280         sslErrors.clear();
1281     }
1282
1283     continueHandshake();
1284     return true;
1285 }
1286
1287 bool QSslSocketBackendPrivate::checkSslErrors()
1288 {
1289     Q_Q(QSslSocket);
1290     if (sslErrors.isEmpty())
1291         return true;
1292
1293     emit q->sslErrors(sslErrors);
1294
1295     bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1296                         || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1297                             && mode == QSslSocket::SslClientMode);
1298     bool doEmitSslError = !verifyErrorsHaveBeenIgnored();
1299     // check whether we need to emit an SSL handshake error
1300     if (doVerifyPeer && doEmitSslError) {
1301         if (q->pauseMode() & QAbstractSocket::PauseOnNotify) {
1302             pauseSocketNotifiers(q);
1303             paused = true;
1304         } else {
1305             q->setErrorString(sslErrors.first().errorString());
1306             q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1307             emit q->error(QAbstractSocket::SslHandshakeFailedError);
1308             plainSocket->disconnectFromHost();
1309         }
1310         return false;
1311     }
1312     return true;
1313 }
1314
1315 #ifdef Q_OS_WIN
1316
1317 void QSslSocketBackendPrivate::fetchCaRootForCert(const QSslCertificate &cert)
1318 {
1319     Q_Q(QSslSocket);
1320     //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1321     //so the request is done in a worker thread.
1322     QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, mode);
1323     QObject::connect(fetcher, SIGNAL(finished(QSslCertificate,QSslCertificate)), q, SLOT(_q_caRootLoaded(QSslCertificate,QSslCertificate)), Qt::QueuedConnection);
1324     QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1325     pauseSocketNotifiers(q);
1326     paused = true;
1327 }
1328
1329 //This is the callback from QWindowsCaRootFetcher, trustedRoot will be invalid (default constructed) if it failed.
1330 void QSslSocketBackendPrivate::_q_caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1331 {
1332     Q_Q(QSslSocket);
1333     if (trustedRoot.isValid()) {
1334         if (s_loadRootCertsOnDemand) {
1335             //Add the new root cert to default cert list for use by future sockets
1336             QSslSocket::addDefaultCaCertificate(trustedRoot);
1337         }
1338         //Add the new root cert to this socket for future connections
1339         q->addCaCertificate(trustedRoot);
1340         //Remove the broken chain ssl errors (as chain is verified by windows)
1341         for (int i=sslErrors.count() - 1; i >= 0; --i) {
1342             if (sslErrors.at(i).certificate() == cert) {
1343                 switch (sslErrors.at(i).error()) {
1344                 case QSslError::UnableToGetLocalIssuerCertificate:
1345                 case QSslError::CertificateUntrusted:
1346                 case QSslError::UnableToVerifyFirstCertificate:
1347                     // error can be ignored if OS says the chain is trusted
1348                     sslErrors.removeAt(i);
1349                     break;
1350                 default:
1351                     // error cannot be ignored
1352                     break;
1353                 }
1354             }
1355         }
1356     }
1357     // Continue with remaining errors
1358     if (plainSocket)
1359         plainSocket->resume();
1360     paused = false;
1361     if (checkSslErrors())
1362         continueHandshake();
1363 }
1364
1365 class QWindowsCaRootFetcherThread : public QThread
1366 {
1367 public:
1368     QWindowsCaRootFetcherThread()
1369     {
1370         qRegisterMetaType<QSslCertificate>();
1371         setObjectName(QStringLiteral("QWindowsCaRootFetcher"));
1372         start();
1373     }
1374     ~QWindowsCaRootFetcherThread()
1375     {
1376         quit();
1377         wait(15500); // worst case, a running request can block for 15 seconds
1378     }
1379 };
1380
1381 Q_GLOBAL_STATIC(QWindowsCaRootFetcherThread, windowsCaRootFetcherThread);
1382
1383 QWindowsCaRootFetcher::QWindowsCaRootFetcher(const QSslCertificate &certificate, QSslSocket::SslMode sslMode)
1384     : cert(certificate), mode(sslMode)
1385 {
1386     moveToThread(windowsCaRootFetcherThread());
1387 }
1388
1389 QWindowsCaRootFetcher::~QWindowsCaRootFetcher()
1390 {
1391 }
1392
1393 void QWindowsCaRootFetcher::start()
1394 {
1395     QByteArray der = cert.toDer();
1396     PCCERT_CONTEXT wincert = CertCreateCertificateContext(X509_ASN_ENCODING, (const BYTE *)der.constData(), der.length());
1397     if (!wincert) {
1398 #ifdef QSSLSOCKET_DEBUG
1399         qDebug("QWindowsCaRootFetcher failed to convert certificate to windows form");
1400 #endif
1401         emit finished(cert, QSslCertificate());
1402         deleteLater();
1403         return;
1404     }
1405
1406     CERT_CHAIN_PARA parameters;
1407     memset(&parameters, 0, sizeof(parameters));
1408     parameters.cbSize = sizeof(parameters);
1409     // set key usage constraint
1410     parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
1411     parameters.RequestedUsage.Usage.cUsageIdentifier = 1;
1412     LPSTR oid = (LPSTR)(mode == QSslSocket::SslClientMode ? szOID_PKIX_KP_SERVER_AUTH : szOID_PKIX_KP_CLIENT_AUTH);
1413     parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &oid;
1414
1415 #ifdef QSSLSOCKET_DEBUG
1416     QElapsedTimer stopwatch;
1417     stopwatch.start();
1418 #endif
1419     PCCERT_CHAIN_CONTEXT chain;
1420     BOOL result = CertGetCertificateChain(
1421         0, //default engine
1422         wincert,
1423         0, //current date/time
1424         0, //default store
1425         &parameters,
1426         0, //default dwFlags
1427         0, //reserved
1428         &chain);
1429 #ifdef QSSLSOCKET_DEBUG
1430     qDebug() << "QWindowsCaRootFetcher" << stopwatch.elapsed() << "ms to get chain";
1431 #endif
1432
1433     QSslCertificate trustedRoot;
1434     if (result) {
1435 #ifdef QSSLSOCKET_DEBUG
1436         qDebug() << "QWindowsCaRootFetcher - examining windows chains";
1437         if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1438             qDebug() << " - TRUSTED";
1439         else
1440             qDebug() << " - NOT TRUSTED" << chain->TrustStatus.dwErrorStatus;
1441         if (chain->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED)
1442             qDebug() << " - SELF SIGNED";
1443         qDebug() << "QSslSocketBackendPrivate::fetchCaRootForCert - dumping simple chains";
1444         for (unsigned int i = 0; i < chain->cChain; i++) {
1445             if (chain->rgpChain[i]->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1446                 qDebug() << " - TRUSTED SIMPLE CHAIN" << i;
1447             else
1448                 qDebug() << " - UNTRUSTED SIMPLE CHAIN" << i << "reason:" << chain->rgpChain[i]->TrustStatus.dwErrorStatus;
1449             for (unsigned int j = 0; j < chain->rgpChain[i]->cElement; j++) {
1450                 QSslCertificate foundCert(QByteArray((const char *)chain->rgpChain[i]->rgpElement[j]->pCertContext->pbCertEncoded
1451                     , chain->rgpChain[i]->rgpElement[j]->pCertContext->cbCertEncoded), QSsl::Der);
1452                 qDebug() << "   - " << foundCert;
1453             }
1454         }
1455         qDebug() << " - and" << chain->cLowerQualityChainContext << "low quality chains"; //expect 0, we haven't asked for them
1456 #endif
1457
1458         //based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa377182%28v=vs.85%29.aspx
1459         //about the final chain rgpChain[cChain-1] which must begin with a trusted root to be valid
1460         if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1461             && chain->cChain > 0) {
1462             const PCERT_SIMPLE_CHAIN finalChain = chain->rgpChain[chain->cChain - 1];
1463             // http://msdn.microsoft.com/en-us/library/windows/desktop/aa377544%28v=vs.85%29.aspx
1464             // rgpElement[0] is the end certificate chain element. rgpElement[cElement-1] is the self-signed "root" certificate element.
1465             if (finalChain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1466                 && finalChain->cElement > 0) {
1467                     trustedRoot = QSslCertificate(QByteArray((const char *)finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->pbCertEncoded
1468                         , finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->cbCertEncoded), QSsl::Der);
1469             }
1470         }
1471         CertFreeCertificateChain(chain);
1472     }
1473     CertFreeCertificateContext(wincert);
1474
1475     emit finished(cert, trustedRoot);
1476     deleteLater();
1477 }
1478 #endif
1479
1480 void QSslSocketBackendPrivate::disconnectFromHost()
1481 {
1482     if (ssl) {
1483         q_SSL_shutdown(ssl);
1484         transmit();
1485     }
1486     plainSocket->disconnectFromHost();
1487 }
1488
1489 void QSslSocketBackendPrivate::disconnected()
1490 {
1491     if (plainSocket->bytesAvailable() <= 0)
1492         destroySslContext();
1493     //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1494     //it will be destroyed when the socket is deleted.
1495 }
1496
1497 QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1498 {
1499     if (!ssl || !ctx)
1500         return QSslCipher();
1501 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1502     // FIXME This is fairly evil, but needed to keep source level compatibility
1503     // with the OpenSSL 0.9.x implementation at maximum -- some other functions
1504     // don't take a const SSL_CIPHER* when they should
1505     SSL_CIPHER *sessionCipher = const_cast<SSL_CIPHER *>(q_SSL_get_current_cipher(ssl));
1506 #else
1507     SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1508 #endif
1509     return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1510 }
1511
1512 void QSslSocketBackendPrivate::continueHandshake()
1513 {
1514     Q_Q(QSslSocket);
1515     // if we have a max read buffer size, reset the plain socket's to match
1516     if (readBufferMaxSize)
1517         plainSocket->setReadBufferSize(readBufferMaxSize);
1518
1519     connectionEncrypted = true;
1520     emit q->encrypted();
1521     if (autoStartHandshake && pendingClose) {
1522         pendingClose = false;
1523         q->disconnectFromHost();
1524     }
1525 }
1526
1527 QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1528 {
1529     ensureInitialized();
1530     QList<QSslCertificate> certificates;
1531     for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1532         if (X509 *entry = q_sk_X509_value(x509, i))
1533             certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1534     }
1535     return certificates;
1536 }
1537
1538 QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1539 {
1540     QString errorString;
1541     unsigned long errNum;
1542     while((errNum = q_ERR_get_error())) {
1543         if (! errorString.isEmpty())
1544             errorString.append(QLatin1String(", "));
1545         const char *error = q_ERR_error_string(errNum, NULL);
1546         errorString.append(QString::fromAscii(error)); // error is ascii according to man ERR_error_string
1547     }
1548     return errorString;
1549 }
1550
1551 bool QSslSocketBackendPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
1552 {
1553     QStringList commonNameList = cert.subjectInfo(QSslCertificate::CommonName);
1554
1555     foreach (const QString &commonName, commonNameList) {
1556         if (isMatchingHostname(commonName.toLower(), peerName.toLower())) {
1557             return true;
1558         }
1559     }
1560
1561     foreach (const QString &altName, cert.subjectAlternativeNames().values(QSsl::DnsEntry)) {
1562         if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
1563             return true;
1564         }
1565     }
1566
1567     return false;
1568 }
1569
1570 bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1571 {
1572     int wildcard = cn.indexOf(QLatin1Char('*'));
1573
1574     // Check this is a wildcard cert, if not then just compare the strings
1575     if (wildcard < 0)
1576         return cn == hostname;
1577
1578     int firstCnDot = cn.indexOf(QLatin1Char('.'));
1579     int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1580
1581     // Check at least 3 components
1582     if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1583         return false;
1584
1585     // Check * is last character of 1st component (ie. there's a following .)
1586     if (wildcard+1 != firstCnDot)
1587         return false;
1588
1589     // Check only one star
1590     if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1591         return false;
1592
1593     // Check characters preceding * (if any) match
1594     if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1595         return false;
1596
1597     // Check characters following first . match
1598     if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1599         return false;
1600
1601     // Check if the hostname is an IP address, if so then wildcards are not allowed
1602     QHostAddress addr(hostname);
1603     if (!addr.isNull())
1604         return false;
1605
1606     // Ok, I guess this was a wildcard CN and the hostname matches.
1607     return true;
1608 }
1609
1610 QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certificateChain, const QString &hostName)
1611 {
1612     QList<QSslError> errors;
1613     if (certificateChain.count() <= 0) {
1614         errors << QSslError(QSslError::UnspecifiedError);
1615         return errors;
1616     }
1617
1618     // Setup the store with the default CA certificates
1619     X509_STORE *certStore = q_X509_STORE_new();
1620     if (!certStore) {
1621         qWarning() << "Unable to create certificate store";
1622         errors << QSslError(QSslError::UnspecifiedError);
1623         return errors;
1624     }
1625
1626     if (s_loadRootCertsOnDemand) {
1627         setDefaultCaCertificates(defaultCaCertificates() + systemCaCertificates());
1628     }
1629
1630     QList<QSslCertificate> expiredCerts;
1631
1632     foreach (const QSslCertificate &caCertificate, QSslSocket::defaultCaCertificates()) {
1633         // add expired certs later, so that the
1634         // valid ones are used before the expired ones
1635         if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
1636             expiredCerts.append(caCertificate);
1637         } else {
1638             q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1639         }
1640     }
1641
1642     bool addExpiredCerts = true;
1643 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
1644     //On Leopard SSL does not work if we add the expired certificates.
1645     if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
1646         addExpiredCerts = false;
1647 #endif
1648     // now add the expired certs
1649     if (addExpiredCerts) {
1650         foreach (const QSslCertificate &caCertificate, expiredCerts) {
1651             q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1652         }
1653     }
1654
1655     QMutexLocker sslErrorListMutexLocker(&_q_sslErrorList()->mutex);
1656
1657     // Register a custom callback to get all verification errors.
1658     X509_STORE_set_verify_cb_func(certStore, q_X509Callback);
1659
1660     // Build the chain of intermediate certificates
1661     STACK_OF(X509) *intermediates = 0;
1662     if (certificateChain.length() > 1) {
1663         intermediates = (STACK_OF(X509) *) q_sk_new_null();
1664
1665         if (!intermediates) {
1666             q_X509_STORE_free(certStore);
1667             errors << QSslError(QSslError::UnspecifiedError);
1668             return errors;
1669         }
1670
1671         bool first = true;
1672         foreach (const QSslCertificate &cert, certificateChain) {
1673             if (first) {
1674                 first = false;
1675                 continue;
1676             }
1677 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1678             q_sk_push( (_STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1679 #else
1680             q_sk_push( (STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1681 #endif
1682         }
1683     }
1684
1685     X509_STORE_CTX *storeContext = q_X509_STORE_CTX_new();
1686     if (!storeContext) {
1687         q_X509_STORE_free(certStore);
1688         errors << QSslError(QSslError::UnspecifiedError);
1689         return errors;
1690     }
1691
1692     if (!q_X509_STORE_CTX_init(storeContext, certStore, reinterpret_cast<X509 *>(certificateChain[0].handle()), intermediates)) {
1693         q_X509_STORE_CTX_free(storeContext);
1694         q_X509_STORE_free(certStore);
1695         errors << QSslError(QSslError::UnspecifiedError);
1696         return errors;
1697     }
1698
1699     // Now we can actually perform the verification of the chain we have built.
1700     // We ignore the result of this function since we process errors via the
1701     // callback.
1702     (void) q_X509_verify_cert(storeContext);
1703
1704     q_X509_STORE_CTX_free(storeContext);
1705 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1706     q_sk_free( (_STACK *) intermediates);
1707 #else
1708     q_sk_free( (STACK *) intermediates);
1709 #endif
1710
1711     // Now process the errors
1712     const QList<QPair<int, int> > errorList = _q_sslErrorList()->errors;
1713     _q_sslErrorList()->errors.clear();
1714
1715     sslErrorListMutexLocker.unlock();
1716
1717     // Translate the errors
1718     if (QSslCertificatePrivate::isBlacklisted(certificateChain[0])) {
1719         QSslError error(QSslError::CertificateBlacklisted, certificateChain[0]);
1720         errors << error;
1721     }
1722
1723     // Check the certificate name against the hostname if one was specified
1724     if ((!hostName.isEmpty()) && (!isMatchingHostname(certificateChain[0], hostName))) {
1725         // No matches in common names or alternate names.
1726         QSslError error(QSslError::HostNameMismatch, certificateChain[0]);
1727         errors << error;
1728     }
1729
1730     // Translate errors from the error list into QSslErrors.
1731     for (int i = 0; i < errorList.size(); ++i) {
1732         const QPair<int, int> &errorAndDepth = errorList.at(i);
1733         int err = errorAndDepth.first;
1734         int depth = errorAndDepth.second;
1735         errors << _q_OpenSSL_to_QSslError(err, certificateChain.value(depth));
1736     }
1737
1738     q_X509_STORE_free(certStore);
1739
1740     return errors;
1741 }
1742
1743 QT_END_NAMESPACE