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