summaryrefslogtreecommitdiffstats
path: root/src/network
diff options
context:
space:
mode:
Diffstat (limited to 'src/network')
-rw-r--r--src/network/access/qhttpnetworkconnection.cpp6
-rw-r--r--src/network/access/qhttpnetworkconnection_p.h6
-rw-r--r--src/network/access/qhttpthreaddelegate.cpp2
-rw-r--r--src/network/access/qnetworkaccessbackend.cpp4
-rw-r--r--src/network/access/qnetworkaccessmanager_p.h2
-rw-r--r--src/network/access/qnetworkdiskcache.cpp1
-rw-r--r--src/network/access/qnetworkreply_p.h10
-rw-r--r--src/network/access/qnetworkreplyhttpimpl.cpp66
-rw-r--r--src/network/access/qnetworkreplyhttpimpl_p.h10
-rw-r--r--src/network/access/qnetworkreplyimpl.cpp32
-rw-r--r--src/network/access/qnetworkreplyimpl_p.h10
-rw-r--r--src/network/access/qspdyprotocolhandler.cpp20
-rw-r--r--src/network/doc/qtnetwork.qdocconf1
-rw-r--r--src/network/kernel/qauthenticator.cpp9
-rw-r--r--src/network/kernel/qauthenticator.h1
-rw-r--r--src/network/kernel/qdnslookup.cpp14
-rw-r--r--src/network/kernel/qdnslookup_winrt.cpp30
-rw-r--r--src/network/kernel/qhostinfo_winrt.cpp43
-rw-r--r--src/network/kernel/qnetworkinterface_winrt.cpp28
-rw-r--r--src/network/network.pro11
-rw-r--r--src/network/socket/qnativesocketengine.cpp4
-rw-r--r--src/network/socket/qnativesocketengine_unix.cpp31
-rw-r--r--src/network/socket/qnativesocketengine_winrt.cpp385
-rw-r--r--src/network/socket/qnativesocketengine_winrt_p.h16
-rw-r--r--src/network/ssl/qasn1element.cpp346
-rw-r--r--src/network/ssl/qasn1element_p.h128
-rw-r--r--src/network/ssl/qsslcertificate.cpp731
-rw-r--r--src/network/ssl/qsslcertificate.h6
-rw-r--r--src/network/ssl/qsslcertificate_openssl.cpp699
-rw-r--r--src/network/ssl/qsslcertificate_p.h42
-rw-r--r--src/network/ssl/qsslcertificate_qt.cpp518
-rw-r--r--src/network/ssl/qsslcertificate_winrt.cpp114
-rw-r--r--src/network/ssl/qsslconfiguration.cpp13
-rw-r--r--src/network/ssl/qsslconfiguration.h1
-rw-r--r--src/network/ssl/qsslconfiguration_p.h4
-rw-r--r--src/network/ssl/qsslcontext_openssl.cpp (renamed from src/network/ssl/qsslcontext.cpp)4
-rw-r--r--src/network/ssl/qsslcontext_openssl_p.h (renamed from src/network/ssl/qsslcontext_p.h)8
-rw-r--r--src/network/ssl/qsslkey.h1
-rw-r--r--src/network/ssl/qsslkey_openssl.cpp224
-rw-r--r--src/network/ssl/qsslkey_p.cpp (renamed from src/network/ssl/qsslkey.cpp)237
-rw-r--r--src/network/ssl/qsslkey_p.h45
-rw-r--r--src/network/ssl/qsslkey_qt.cpp246
-rw-r--r--src/network/ssl/qsslkey_winrt.cpp161
-rw-r--r--src/network/ssl/qsslsocket.cpp112
-rw-r--r--src/network/ssl/qsslsocket.h5
-rw-r--r--src/network/ssl/qsslsocket_openssl.cpp160
-rw-r--r--src/network/ssl/qsslsocket_openssl_p.h7
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols.cpp16
-rw-r--r--src/network/ssl/qsslsocket_openssl_symbols_p.h10
-rw-r--r--src/network/ssl/qsslsocket_p.h25
-rw-r--r--src/network/ssl/qsslsocket_winrt.cpp688
-rw-r--r--src/network/ssl/qsslsocket_winrt_p.h111
-rw-r--r--src/network/ssl/ssl.pri43
53 files changed, 4180 insertions, 1267 deletions
diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp
index 360f9722c7..7ff6bffed3 100644
--- a/src/network/access/qhttpnetworkconnection.cpp
+++ b/src/network/access/qhttpnetworkconnection.cpp
@@ -1203,7 +1203,7 @@ QHttpNetworkConnection::QHttpNetworkConnection(const QString &hostName, quint16
: QObject(*(new QHttpNetworkConnectionPrivate(hostName, port, encrypt, connectionType)), parent)
{
Q_D(QHttpNetworkConnection);
- d->networkSession = networkSession;
+ d->networkSession = qMove(networkSession);
d->init();
}
@@ -1215,7 +1215,7 @@ QHttpNetworkConnection::QHttpNetworkConnection(quint16 connectionCount, const QS
connectionType)), parent)
{
Q_D(QHttpNetworkConnection);
- d->networkSession = networkSession;
+ d->networkSession = qMove(networkSession);
d->init();
}
#else
@@ -1339,7 +1339,7 @@ QSharedPointer<QSslContext> QHttpNetworkConnection::sslContext()
void QHttpNetworkConnection::setSslContext(QSharedPointer<QSslContext> context)
{
Q_D(QHttpNetworkConnection);
- d->sslContext = context;
+ d->sslContext = qMove(context);
}
void QHttpNetworkConnection::ignoreSslErrors(int channel)
diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h
index 42114ae9d6..379ed5acae 100644
--- a/src/network/access/qhttpnetworkconnection_p.h
+++ b/src/network/access/qhttpnetworkconnection_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -73,7 +73,9 @@
#ifndef QT_NO_HTTP
#ifndef QT_NO_SSL
-# include <private/qsslcontext_p.h>
+#ifndef QT_NO_OPENSSL
+# include <private/qsslcontext_openssl_p.h>
+#endif
# include <private/qsslsocket_p.h>
# include <QtNetwork/qsslsocket.h>
# include <QtNetwork/qsslerror.h>
diff --git a/src/network/access/qhttpthreaddelegate.cpp b/src/network/access/qhttpthreaddelegate.cpp
index 76107d3110..8743989dec 100644
--- a/src/network/access/qhttpthreaddelegate.cpp
+++ b/src/network/access/qhttpthreaddelegate.cpp
@@ -188,7 +188,7 @@ public:
QHttpNetworkConnection::ConnectionType connectionType,
QSharedPointer<QNetworkSession> networkSession)
: QHttpNetworkConnection(hostName, port, encrypt, connectionType, /*parent=*/0,
- networkSession)
+ qMove(networkSession))
#endif
{
setExpires(true);
diff --git a/src/network/access/qnetworkaccessbackend.cpp b/src/network/access/qnetworkaccessbackend.cpp
index b4aaca0851..acaba33dee 100644
--- a/src/network/access/qnetworkaccessbackend.cpp
+++ b/src/network/access/qnetworkaccessbackend.cpp
@@ -130,9 +130,9 @@ QStringList QNetworkAccessManagerPrivate::backendSupportedSchemes() const
QNonContiguousByteDevice* QNetworkAccessBackend::createUploadByteDevice()
{
if (reply->outgoingDataBuffer)
- uploadByteDevice = QSharedPointer<QNonContiguousByteDevice>(QNonContiguousByteDeviceFactory::create(reply->outgoingDataBuffer));
+ uploadByteDevice = QNonContiguousByteDeviceFactory::createShared(reply->outgoingDataBuffer);
else if (reply->outgoingData) {
- uploadByteDevice = QSharedPointer<QNonContiguousByteDevice>(QNonContiguousByteDeviceFactory::create(reply->outgoingData));
+ uploadByteDevice = QNonContiguousByteDeviceFactory::createShared(reply->outgoingData);
} else {
return 0;
}
diff --git a/src/network/access/qnetworkaccessmanager_p.h b/src/network/access/qnetworkaccessmanager_p.h
index 9528330aae..bd5a6faeef 100644
--- a/src/network/access/qnetworkaccessmanager_p.h
+++ b/src/network/access/qnetworkaccessmanager_p.h
@@ -92,7 +92,7 @@ public:
initializeSession(true),
#endif
cookieJarCreated(false),
- authenticationManager(new QNetworkAccessAuthenticationManager)
+ authenticationManager(QSharedPointer<QNetworkAccessAuthenticationManager>::create())
{ }
~QNetworkAccessManagerPrivate();
diff --git a/src/network/access/qnetworkdiskcache.cpp b/src/network/access/qnetworkdiskcache.cpp
index 86a3b20a9c..2ecabd593a 100644
--- a/src/network/access/qnetworkdiskcache.cpp
+++ b/src/network/access/qnetworkdiskcache.cpp
@@ -48,6 +48,7 @@
#include <qfile.h>
#include <qdir.h>
+#include <qdatastream.h>
#include <qdatetime.h>
#include <qdiriterator.h>
#include <qurl.h>
diff --git a/src/network/access/qnetworkreply_p.h b/src/network/access/qnetworkreply_p.h
index ad11ef3964..55d3d85592 100644
--- a/src/network/access/qnetworkreply_p.h
+++ b/src/network/access/qnetworkreply_p.h
@@ -65,6 +65,16 @@ QT_BEGIN_NAMESPACE
class QNetworkReplyPrivate: public QIODevicePrivate, public QNetworkHeadersPrivate
{
public:
+ enum State {
+ Idle, // The reply is idle.
+ Buffering, // The reply is buffering outgoing data.
+ Working, // The reply is uploading/downloading data.
+ Finished, // The reply has finished.
+ Aborted, // The reply has been aborted.
+ WaitingForSession, // The reply is waiting for the session to open before connecting.
+ Reconnecting // The reply will reconnect to once roaming has completed.
+ };
+
QNetworkReplyPrivate();
QNetworkRequest request;
QUrl url;
diff --git a/src/network/access/qnetworkreplyhttpimpl.cpp b/src/network/access/qnetworkreplyhttpimpl.cpp
index 4efb2f6a2a..796f51b9b1 100644
--- a/src/network/access/qnetworkreplyhttpimpl.cpp
+++ b/src/network/access/qnetworkreplyhttpimpl.cpp
@@ -194,7 +194,7 @@ QNetworkReplyHttpImpl::QNetworkReplyHttpImpl(QNetworkAccessManager* const manage
if (d->synchronous && outgoingData) {
// The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
// Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
- d->outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
+ d->outgoingDataBuffer = QSharedPointer<QRingBuffer>::create();
qint64 previousDataSize = 0;
do {
previousDataSize = d->outgoingDataBuffer->size();
@@ -250,8 +250,8 @@ void QNetworkReplyHttpImpl::close()
{
Q_D(QNetworkReplyHttpImpl);
- if (d->state == QNetworkReplyHttpImplPrivate::Aborted ||
- d->state == QNetworkReplyHttpImplPrivate::Finished)
+ if (d->state == QNetworkReplyPrivate::Aborted ||
+ d->state == QNetworkReplyPrivate::Finished)
return;
// According to the documentation close only stops the download
@@ -268,19 +268,23 @@ void QNetworkReplyHttpImpl::abort()
{
Q_D(QNetworkReplyHttpImpl);
// FIXME
- if (d->state == QNetworkReplyHttpImplPrivate::Finished || d->state == QNetworkReplyHttpImplPrivate::Aborted)
+ if (d->state == QNetworkReplyPrivate::Finished || d->state == QNetworkReplyPrivate::Aborted)
return;
QNetworkReply::close();
- if (d->state != QNetworkReplyHttpImplPrivate::Finished) {
+ if (d->state != QNetworkReplyPrivate::Finished) {
// call finished which will emit signals
// FIXME shouldn't this be emitted Queued?
d->error(OperationCanceledError, tr("Operation canceled"));
+
+ // If state is WaitingForSession, calling finished has no effect
+ if (d->state == QNetworkReplyPrivate::WaitingForSession)
+ d->state = QNetworkReplyPrivate::Working;
d->finished();
}
- d->state = QNetworkReplyHttpImplPrivate::Aborted;
+ d->state = QNetworkReplyPrivate::Aborted;
emit abortHttpRequest();
}
@@ -440,8 +444,8 @@ QNetworkReplyHttpImplPrivate::QNetworkReplyHttpImplPrivate()
, downloadBufferReadPosition(0)
, downloadBufferCurrentSize(0)
, downloadZerocopyBuffer(0)
- , pendingDownloadDataEmissions(new QAtomicInt())
- , pendingDownloadProgressEmissions(new QAtomicInt())
+ , pendingDownloadDataEmissions(QSharedPointer<QAtomicInt>::create())
+ , pendingDownloadProgressEmissions(QSharedPointer<QAtomicInt>::create())
#ifndef QT_NO_SSL
, pendingIgnoreAllSslErrors(false)
#endif
@@ -556,23 +560,21 @@ bool QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(QHttpNetworkRequest &h
int resident_time = now - response_time;
int current_age = corrected_initial_age + resident_time;
+ int freshness_lifetime = 0;
+
// RFC 2616 13.2.4 Expiration Calculations
- if (!expirationDate.isValid()) {
- if (lastModified.isValid()) {
- int diff = currentDateTime.secsTo(lastModified);
- expirationDate = lastModified.addSecs(diff / 10);
- if (httpRequest.headerField("Warning").isEmpty()) {
- QDateTime dt;
- dt.setTime_t(current_age);
- if (dt.daysTo(currentDateTime) > 1)
- httpRequest.setHeaderField("Warning", "113");
- }
+ if (lastModified.isValid() && dateHeader.isValid()) {
+ int diff = lastModified.secsTo(dateHeader);
+ freshness_lifetime = diff / 10;
+ if (httpRequest.headerField("Warning").isEmpty()) {
+ QDateTime dt = currentDateTime.addSecs(current_age);
+ if (currentDateTime.daysTo(dt) > 1)
+ httpRequest.setHeaderField("Warning", "113");
}
}
- // the cache-saving code below sets the expirationDate with date+max_age
- // if "max-age" is present, or to Expires otherwise
- int freshness_lifetime = dateHeader.secsTo(expirationDate);
+ // the cache-saving code below sets the freshness_lifetime with (dateHeader - last_modified) / 10
+ // if "last-modified" is present, or to Expires otherwise
response_is_fresh = (freshness_lifetime > current_age);
} else {
// expiration date was calculated earlier (e.g. when storing object to the cache)
@@ -1583,8 +1585,14 @@ bool QNetworkReplyHttpImplPrivate::start()
q, SLOT(_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies)));
postRequest();
return true;
+ } else if (synchronous) {
+ // Command line applications using the synchronous path such as xmlpatterns may need an extra push.
+ networkSession->open();
+ if (networkSession->waitForOpened()) {
+ postRequest();
+ return true;
+ }
}
-
return false;
#endif
}
@@ -1743,7 +1751,7 @@ void QNetworkReplyHttpImplPrivate::_q_bufferOutgoingData()
if (!outgoingDataBuffer) {
// first call, create our buffer
- outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
+ outgoingDataBuffer = QSharedPointer<QRingBuffer>::create();
QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
@@ -1796,13 +1804,13 @@ void QNetworkReplyHttpImplPrivate::_q_networkSessionConnected()
return;
switch (state) {
- case QNetworkReplyImplPrivate::Buffering:
- case QNetworkReplyImplPrivate::Working:
- case QNetworkReplyImplPrivate::Reconnecting:
+ case QNetworkReplyPrivate::Buffering:
+ case QNetworkReplyPrivate::Working:
+ case QNetworkReplyPrivate::Reconnecting:
// Migrate existing downloads to new network connection.
migrateBackend();
break;
- case QNetworkReplyImplPrivate::WaitingForSession:
+ case QNetworkReplyPrivate::WaitingForSession:
// Start waiting requests.
QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
break;
@@ -1872,9 +1880,9 @@ QNonContiguousByteDevice* QNetworkReplyHttpImplPrivate::createUploadByteDevice()
Q_Q(QNetworkReplyHttpImpl);
if (outgoingDataBuffer)
- uploadByteDevice = QSharedPointer<QNonContiguousByteDevice>(QNonContiguousByteDeviceFactory::create(outgoingDataBuffer));
+ uploadByteDevice = QNonContiguousByteDeviceFactory::createShared(outgoingDataBuffer);
else if (outgoingData) {
- uploadByteDevice = QSharedPointer<QNonContiguousByteDevice>(QNonContiguousByteDeviceFactory::create(outgoingData));
+ uploadByteDevice = QNonContiguousByteDeviceFactory::createShared(outgoingData);
} else {
return 0;
}
diff --git a/src/network/access/qnetworkreplyhttpimpl_p.h b/src/network/access/qnetworkreplyhttpimpl_p.h
index 06a5383ae4..b7de947a29 100644
--- a/src/network/access/qnetworkreplyhttpimpl_p.h
+++ b/src/network/access/qnetworkreplyhttpimpl_p.h
@@ -160,16 +160,6 @@ public:
static QHttpNetworkRequest::Priority convert(const QNetworkRequest::Priority& prio);
- enum State {
- Idle, // The reply is idle.
- Buffering, // The reply is buffering outgoing data.
- Working, // The reply is uploading/downloading data.
- Finished, // The reply has finished.
- Aborted, // The reply has been aborted.
- WaitingForSession, // The reply is waiting for the session to open before connecting.
- Reconnecting // The reply will reconnect to once roaming has completed.
- };
-
QNetworkReplyHttpImplPrivate();
~QNetworkReplyHttpImplPrivate();
diff --git a/src/network/access/qnetworkreplyimpl.cpp b/src/network/access/qnetworkreplyimpl.cpp
index f51b85cba0..be0ddf1388 100644
--- a/src/network/access/qnetworkreplyimpl.cpp
+++ b/src/network/access/qnetworkreplyimpl.cpp
@@ -248,7 +248,7 @@ void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
if (!outgoingDataBuffer) {
// first call, create our buffer
- outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
+ outgoingDataBuffer = QSharedPointer<QRingBuffer>::create();
QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
@@ -301,13 +301,13 @@ void QNetworkReplyImplPrivate::_q_networkSessionConnected()
return;
switch (state) {
- case QNetworkReplyImplPrivate::Buffering:
- case QNetworkReplyImplPrivate::Working:
- case QNetworkReplyImplPrivate::Reconnecting:
+ case QNetworkReplyPrivate::Buffering:
+ case QNetworkReplyPrivate::Working:
+ case QNetworkReplyPrivate::Reconnecting:
// Migrate existing downloads to new network connection.
migrateBackend();
break;
- case QNetworkReplyImplPrivate::WaitingForSession:
+ case QNetworkReplyPrivate::WaitingForSession:
// Start waiting requests.
QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
break;
@@ -367,7 +367,7 @@ void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const
// The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
// Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
if (synchronousHttpAttribute.toBool() && outgoingData) {
- outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
+ outgoingDataBuffer = QSharedPointer<QRingBuffer>::create();
qint64 previousDataSize = 0;
do {
previousDataSize = outgoingDataBuffer->size();
@@ -916,7 +916,7 @@ QNetworkReplyImpl::~QNetworkReplyImpl()
void QNetworkReplyImpl::abort()
{
Q_D(QNetworkReplyImpl);
- if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
+ if (d->state == QNetworkReplyPrivate::Finished || d->state == QNetworkReplyPrivate::Aborted)
return;
// stop both upload and download
@@ -927,14 +927,14 @@ void QNetworkReplyImpl::abort()
QNetworkReply::close();
- if (d->state != QNetworkReplyImplPrivate::Finished) {
+ if (d->state != QNetworkReplyPrivate::Finished) {
// call finished which will emit signals
d->error(OperationCanceledError, tr("Operation canceled"));
- if (d->state == QNetworkReplyImplPrivate::WaitingForSession)
- d->state = QNetworkReplyImplPrivate::Working;
+ if (d->state == QNetworkReplyPrivate::WaitingForSession)
+ d->state = QNetworkReplyPrivate::Working;
d->finished();
}
- d->state = QNetworkReplyImplPrivate::Aborted;
+ d->state = QNetworkReplyPrivate::Aborted;
// finished may access the backend
if (d->backend) {
@@ -946,8 +946,8 @@ void QNetworkReplyImpl::abort()
void QNetworkReplyImpl::close()
{
Q_D(QNetworkReplyImpl);
- if (d->state == QNetworkReplyImplPrivate::Aborted ||
- d->state == QNetworkReplyImplPrivate::Finished)
+ if (d->state == QNetworkReplyPrivate::Aborted ||
+ d->state == QNetworkReplyPrivate::Finished)
return;
// stop the download
@@ -1041,7 +1041,7 @@ qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
if (d->downloadBuffer) {
qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
if (maxAvail == 0)
- return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
+ return d->state == QNetworkReplyPrivate::Finished ? -1 : 0;
// FIXME what about "Aborted" state?
memcpy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
d->downloadBufferReadPosition += maxAvail;
@@ -1050,7 +1050,7 @@ qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
if (d->readBuffer.isEmpty())
- return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
+ return d->state == QNetworkReplyPrivate::Finished ? -1 : 0;
// FIXME what about "Aborted" state?
d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
@@ -1101,7 +1101,7 @@ bool QNetworkReplyImplPrivate::migrateBackend()
if (!backend->canResume())
return false;
- state = QNetworkReplyImplPrivate::Reconnecting;
+ state = QNetworkReplyPrivate::Reconnecting;
if (backend) {
delete backend;
diff --git a/src/network/access/qnetworkreplyimpl_p.h b/src/network/access/qnetworkreplyimpl_p.h
index 9edc0f6b59..3340dcc91e 100644
--- a/src/network/access/qnetworkreplyimpl_p.h
+++ b/src/network/access/qnetworkreplyimpl_p.h
@@ -118,16 +118,6 @@ public:
NotifyCopyFinished
};
- enum State {
- Idle, // The reply is idle.
- Buffering, // The reply is buffering outgoing data.
- Working, // The reply is uploading/downloading data.
- Finished, // The reply has finished.
- Aborted, // The reply has been aborted.
- WaitingForSession, // The reply is waiting for the session to open before connecting.
- Reconnecting // The reply will reconnect to once roaming has completed.
- };
-
typedef QQueue<InternalNotifications> NotificationQueue;
QNetworkReplyImplPrivate();
diff --git a/src/network/access/qspdyprotocolhandler.cpp b/src/network/access/qspdyprotocolhandler.cpp
index 32a804e9f4..ab703981ee 100644
--- a/src/network/access/qspdyprotocolhandler.cpp
+++ b/src/network/access/qspdyprotocolhandler.cpp
@@ -506,25 +506,7 @@ QByteArray QSpdyProtocolHandler::composeHeader(const QHttpNetworkRequest &reques
#endif
uncompressedHeader.append(headerField(":version", "HTTP/1.1"));
- QHostAddress add; // ### unify with the host parsing from QHttpNetworkConnection
- QByteArray host;
- QString hostName = m_connection->hostName();
- if (add.setAddress(hostName)) {
- if (add.protocol() == QAbstractSocket::IPv6Protocol)
- host = "[" + hostName.toLatin1() + "]"; //format the ipv6 in the standard way
- else
- host = hostName.toLatin1();
-
- } else {
- host = QUrl::toAce(hostName);
- }
-
- int port = request.url().port();
- if (port != -1) {
- host += ':';
- host += QByteArray::number(port);
- }
- uncompressedHeader.append(headerField(":host", host));
+ uncompressedHeader.append(headerField(":host", request.url().authority(QUrl::FullyEncoded | QUrl::RemoveUserInfo).toLatin1()));
uncompressedHeader.append(headerField(":scheme", request.url().scheme().toLatin1()));
diff --git a/src/network/doc/qtnetwork.qdocconf b/src/network/doc/qtnetwork.qdocconf
index 33d6c24461..522d71fd27 100644
--- a/src/network/doc/qtnetwork.qdocconf
+++ b/src/network/doc/qtnetwork.qdocconf
@@ -2,7 +2,6 @@ include($QT_INSTALL_DOCS/global/qt-module-defaults.qdocconf)
project = QtNetwork
description = Qt Network Reference Documentation
-url = http://qt-project.org/doc/qt-$QT_VER
version = $QT_VERSION
examplesinstallpath = network
diff --git a/src/network/kernel/qauthenticator.cpp b/src/network/kernel/qauthenticator.cpp
index c582e95b1c..c4c7abb240 100644
--- a/src/network/kernel/qauthenticator.cpp
+++ b/src/network/kernel/qauthenticator.cpp
@@ -282,6 +282,15 @@ QString QAuthenticator::realm() const
}
/*!
+ \internal
+*/
+void QAuthenticator::setRealm(const QString &realm)
+{
+ detach();
+ d->realm = realm;
+}
+
+/*!
\since 4.7
Returns the value related to option \a opt if it was set by the server.
See \l{QAuthenticator#Options} for more information on incoming options.
diff --git a/src/network/kernel/qauthenticator.h b/src/network/kernel/qauthenticator.h
index 4d96104bc0..2f440d660d 100644
--- a/src/network/kernel/qauthenticator.h
+++ b/src/network/kernel/qauthenticator.h
@@ -70,6 +70,7 @@ public:
void setPassword(const QString &password);
QString realm() const;
+ void setRealm(const QString &realm);
QVariant option(const QString &opt) const;
QVariantHash options() const;
diff --git a/src/network/kernel/qdnslookup.cpp b/src/network/kernel/qdnslookup.cpp
index e111a190cb..b7e6bad0a7 100644
--- a/src/network/kernel/qdnslookup.cpp
+++ b/src/network/kernel/qdnslookup.cpp
@@ -283,9 +283,21 @@ QDnsLookup::QDnsLookup(Type type, const QString &name, QObject *parent)
/*!
\fn QDnsLookup::QDnsLookup(Type type, const QString &name, const QHostAddress &nameserver, QObject *parent)
- \internal
+ \since 5.4
+ Constructs a QDnsLookup object for the given \a type, \a name and
+ \a nameserver and sets \a parent as the parent object.
*/
+QDnsLookup::QDnsLookup(Type type, const QString &name, const QHostAddress &nameserver, QObject *parent)
+ : QObject(*new QDnsLookupPrivate, parent)
+{
+ Q_D(QDnsLookup);
+ qRegisterMetaType<QDnsLookupReply>();
+ d->name = name;
+ d->type = type;
+ d->nameserver = nameserver;
+}
+
/*!
Destroys the QDnsLookup object.
diff --git a/src/network/kernel/qdnslookup_winrt.cpp b/src/network/kernel/qdnslookup_winrt.cpp
index e2a5ba2f37..52a8c3a530 100644
--- a/src/network/kernel/qdnslookup_winrt.cpp
+++ b/src/network/kernel/qdnslookup_winrt.cpp
@@ -81,31 +81,28 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
return;
}
- IHostNameFactory *hostnameFactory;
-
- HStringReference classId(RuntimeClass_Windows_Networking_HostName);
- if (FAILED(GetActivationFactory(classId.Get(), &hostnameFactory))) {
+ ComPtr<IHostNameFactory> hostnameFactory;
+ HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
+ IID_PPV_ARGS(&hostnameFactory));
+ if (FAILED(hr)) {
reply->error = QDnsLookup::ResolverError;
reply->errorString = QLatin1String("Could not obtain hostname factory");
return;
}
- IHostName *host;
+ ComPtr<IHostName> host;
HStringReference hostNameRef((const wchar_t*)aceHostname.utf16());
hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
- hostnameFactory->Release();
- IDatagramSocketStatics *datagramSocketStatics;
+ ComPtr<IDatagramSocketStatics> datagramSocketStatics;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
- IAsyncOperation<IVectorView<EndpointPair*> *> *op;
- datagramSocketStatics->GetEndpointPairsAsync(host,
+ ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
+ datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
HString::MakeReference(L"0").Get(),
&op);
- datagramSocketStatics->Release();
- host->Release();
- IVectorView<EndpointPair*> *endpointPairs = 0;
- HRESULT hr = op->GetResults(&endpointPairs);
+ ComPtr<IVectorView<EndpointPair *>> endpointPairs;
+ hr = op->GetResults(&endpointPairs);
int waitCount = 0;
while (hr == E_ILLEGAL_METHOD_CALL) {
WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
@@ -113,7 +110,6 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
if (++waitCount > 1200) // Wait for 1 minute max
return;
}
- op->Release();
if (!endpointPairs)
return;
@@ -123,11 +119,10 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
// endpoint pairs might contain duplicates so we temporarily store addresses in a QSet
QSet<QHostAddress> addresses;
for (unsigned int i = 0; i < size; ++i) {
- IEndpointPair *endpointpair;
+ ComPtr<IEndpointPair> endpointpair;
endpointPairs->GetAt(i, &endpointpair);
- IHostName *remoteHost;
+ ComPtr<IHostName> remoteHost;
endpointpair->get_RemoteHostName(&remoteHost);
- endpointpair->Release();
HostNameType type;
remoteHost->get_Type(&type);
if (type == HostNameType_Bluetooth || type == HostNameType_DomainName
@@ -138,7 +133,6 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
HString name;
remoteHost->get_CanonicalName(name.GetAddressOf());
- remoteHost->Release();
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
addresses.insert(QHostAddress(QString::fromWCharArray(rawString, length)));
diff --git a/src/network/kernel/qhostinfo_winrt.cpp b/src/network/kernel/qhostinfo_winrt.cpp
index e02cd98e08..26f6585c32 100644
--- a/src/network/kernel/qhostinfo_winrt.cpp
+++ b/src/network/kernel/qhostinfo_winrt.cpp
@@ -80,29 +80,25 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
return results;
}
- IHostNameFactory *hostnameFactory;
+ ComPtr<IHostNameFactory> hostnameFactory;
+ HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
+ IID_PPV_ARGS(&hostnameFactory));
+ Q_ASSERT_X(SUCCEEDED(hr), Q_FUNC_INFO, qPrintable(qt_error_string(hr)));
- HStringReference classId(RuntimeClass_Windows_Networking_HostName);
- if (FAILED(GetActivationFactory(classId.Get(), &hostnameFactory)))
- Q_ASSERT_X(false, "QHostInfoAgent", "Could not obtain hostname factory.");
-
- IHostName *host;
+ ComPtr<IHostName> host;
HStringReference hostNameRef((const wchar_t*)hostName.utf16());
hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
- hostnameFactory->Release();
- IDatagramSocketStatics *datagramSocketStatics;
+ ComPtr<IDatagramSocketStatics> datagramSocketStatics;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
- IAsyncOperation<IVectorView<EndpointPair*> *> *op;
- datagramSocketStatics->GetEndpointPairsAsync(host,
+ ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
+ datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
HString::MakeReference(L"0").Get(),
&op);
- datagramSocketStatics->Release();
- host->Release();
- IVectorView<EndpointPair*> *endpointPairs = 0;
- HRESULT hr = op->GetResults(&endpointPairs);
+ ComPtr<IVectorView<EndpointPair *>> endpointPairs;
+ hr = op->GetResults(&endpointPairs);
int waitCount = 0;
while (hr == E_ILLEGAL_METHOD_CALL) {
WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
@@ -110,7 +106,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
if (++waitCount > 1200) // Wait for 1 minute max
return results;
}
- op->Release();
if (!endpointPairs)
return results;
@@ -119,11 +114,10 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
endpointPairs->get_Size(&size);
QList<QHostAddress> addresses;
for (unsigned int i = 0; i < size; ++i) {
- IEndpointPair *endpointpair;
+ ComPtr<IEndpointPair> endpointpair;
endpointPairs->GetAt(i, &endpointpair);
- IHostName *remoteHost;
+ ComPtr<IHostName> remoteHost;
endpointpair->get_RemoteHostName(&remoteHost);
- endpointpair->Release();
if (!remoteHost)
continue;
HostNameType type;
@@ -133,7 +127,6 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
HString name;
remoteHost->get_CanonicalName(name.GetAddressOf());
- remoteHost->Release();
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
QHostAddress addr;
@@ -148,12 +141,11 @@ QHostInfo QHostInfoAgent::fromName(const QString &hostName)
QString QHostInfo::localHostName()
{
- INetworkInformationStatics *statics;
+ ComPtr<INetworkInformationStatics> statics;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &statics);
- IVectorView<HostName*> *hostNames = 0;
+ ComPtr<IVectorView<HostName *>> hostNames;
statics->GetHostNames(&hostNames);
- statics->Release();
if (!hostNames)
return QString();
@@ -163,7 +155,7 @@ QString QHostInfo::localHostName()
return QString();
for (unsigned int i = 0; i < size; ++i) {
- IHostName *hostName;
+ ComPtr<IHostName> hostName;
hostNames->GetAt(i, &hostName);
HostNameType type;
hostName->get_Type(&type);
@@ -172,18 +164,15 @@ QString QHostInfo::localHostName()
HString name;
hostName->get_CanonicalName(name.GetAddressOf());
- hostName->Release();
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
return QString::fromWCharArray(rawString, length);
}
- IHostName *firstHost;
+ ComPtr<IHostName> firstHost;
hostNames->GetAt(0, &firstHost);
- hostNames->Release();
HString name;
firstHost->get_CanonicalName(name.GetAddressOf());
- firstHost->Release();
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
return QString::fromWCharArray(rawString, length);
diff --git a/src/network/kernel/qnetworkinterface_winrt.cpp b/src/network/kernel/qnetworkinterface_winrt.cpp
index 48a96928a8..c8547411eb 100644
--- a/src/network/kernel/qnetworkinterface_winrt.cpp
+++ b/src/network/kernel/qnetworkinterface_winrt.cpp
@@ -73,12 +73,11 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
QList<HostNameInfo> hostList;
- INetworkInformationStatics *hostNameStatics;
+ ComPtr<INetworkInformationStatics> hostNameStatics;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &hostNameStatics);
- IVectorView<HostName*> *hostNames = 0;
+ ComPtr<IVectorView<HostName *>> hostNames;
hostNameStatics->GetHostNames(&hostNames);
- hostNameStatics->Release();
if (!hostNames)
return interfaces;
@@ -86,7 +85,7 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
hostNames->get_Size(&hostNameCount);
for (unsigned i = 0; i < hostNameCount; ++i) {
HostNameInfo hostInfo;
- IHostName *hostName;
+ ComPtr<IHostName> hostName;
hostNames->GetAt(i, &hostName);
HostNameType type;
@@ -94,20 +93,17 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
if (type == HostNameType_DomainName)
continue;
- IIPInformation *ipInformation;
+ ComPtr<IIPInformation> ipInformation;
hostName->get_IPInformation(&ipInformation);
- INetworkAdapter *currentAdapter;
+ ComPtr<INetworkAdapter> currentAdapter;
ipInformation->get_NetworkAdapter(&currentAdapter);
currentAdapter->get_NetworkAdapterId(&hostInfo.adapterId);
- currentAdapter->Release();
- IReference<unsigned char> *prefixLengthReference;
+ ComPtr<IReference<unsigned char>> prefixLengthReference;
ipInformation->get_PrefixLength(&prefixLengthReference);
- ipInformation->Release();
prefixLengthReference->get_Value(&hostInfo.prefixLength);
- prefixLengthReference->Release();
// invalid prefixes
if ((type == HostNameType_Ipv4 && hostInfo.prefixLength > 32)
@@ -116,20 +112,17 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
HString name;
hostName->get_CanonicalName(name.GetAddressOf());
- hostName->Release();
UINT32 length;
PCWSTR rawString = name.GetRawBuffer(&length);
hostInfo.address = QString::fromWCharArray(rawString, length);
hostList << hostInfo;
}
- hostNames->Release();
INetworkInformationStatics *networkInfoStatics;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &networkInfoStatics);
- IVectorView<ConnectionProfile *> *connectionProfiles = 0;
+ ComPtr<IVectorView<ConnectionProfile *>> connectionProfiles;
networkInfoStatics->GetConnectionProfiles(&connectionProfiles);
- networkInfoStatics->Release();
if (!connectionProfiles)
return interfaces;
@@ -139,7 +132,7 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
interfaces << iface;
- IConnectionProfile *profile;
+ ComPtr<IConnectionProfile> profile;
connectionProfiles->GetAt(i, &profile);
NetworkConnectivityLevel connectivityLevel;
@@ -147,16 +140,14 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
if (connectivityLevel != NetworkConnectivityLevel_None)
iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
- INetworkAdapter *adapter;
+ ComPtr<INetworkAdapter> adapter;
profile->get_NetworkAdapter(&adapter);
- profile->Release();
UINT32 type;
adapter->get_IanaInterfaceType(&type);
if (type == 23)
iface->flags |= QNetworkInterface::IsPointToPoint;
GUID id;
adapter->get_NetworkAdapterId(&id);
- adapter->Release();
OLECHAR adapterName[39]={0};
StringFromGUID2(id, adapterName, 39);
iface->name = QString::fromWCharArray(adapterName);
@@ -179,7 +170,6 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
--i;
}
}
- connectionProfiles->Release();
return interfaces;
}
diff --git a/src/network/network.pro b/src/network/network.pro
index 79e357e0cb..4cced923f7 100644
--- a/src/network/network.pro
+++ b/src/network/network.pro
@@ -25,3 +25,14 @@ include(socket/socket.pri)
include(ssl/ssl.pri)
QMAKE_LIBS += $$QMAKE_LIBS_NETWORK
+
+ANDROID_BUNDLED_JAR_DEPENDENCIES = \
+ jar/QtAndroidBearer-bundled.jar
+ANDROID_JAR_DEPENDENCIES = \
+ jar/QtAndroidBearer.jar
+ANDROID_LIB_DEPENDENCIES = \
+ plugins/bearer/libqandroidbearer.so
+MODULE_PLUGIN_TYPES = \
+ bearer
+ANDROID_PERMISSIONS += \
+ android.permission.ACCESS_NETWORK_STATE
diff --git a/src/network/socket/qnativesocketengine.cpp b/src/network/socket/qnativesocketengine.cpp
index 6bf8626f97..fc2bd18793 100644
--- a/src/network/socket/qnativesocketengine.cpp
+++ b/src/network/socket/qnativesocketengine.cpp
@@ -430,8 +430,8 @@ bool QNativeSocketEngine::initialize(qintptr socketDescriptor, QAbstractSocket::
// determine socket type and protocol
if (!d->fetchConnectionParameters()) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
- qDebug("QNativeSocketEngine::initialize(socketDescriptor == %i) failed: %s",
- socketDescriptor, d->socketErrorString.toLatin1().constData());
+ qDebug() << "QNativeSocketEngine::initialize(socketDescriptor) failed:"
+ << socketDescriptor << d->socketErrorString;
#endif
d->socketDescriptor = -1;
return false;
diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp
index 65244ce9cf..871f163a4a 100644
--- a/src/network/socket/qnativesocketengine_unix.cpp
+++ b/src/network/socket/qnativesocketengine_unix.cpp
@@ -154,7 +154,8 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
}
if (socket <= 0) {
- switch (errno) {
+ int ecopy = errno;
+ switch (ecopy) {
case EPROTONOSUPPORT:
case EAFNOSUPPORT:
case EINVAL:
@@ -173,9 +174,20 @@ bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType soc
break;
}
+#if defined (QNATIVESOCKETENGINE_DEBUG)
+ qDebug("QNativeSocketEnginePrivate::createNewSocket(%d, %d) == false (%s)",
+ socketType, socketProtocol,
+ strerror(ecopy));
+#endif
+
return false;
}
+#if defined (QNATIVESOCKETENGINE_DEBUG)
+ qDebug("QNativeSocketEnginePrivate::createNewSocket(%d, %d) == true",
+ socketType, socketProtocol);
+#endif
+
socketDescriptor = socket;
return true;
}
@@ -365,7 +377,7 @@ bool QNativeSocketEnginePrivate::setOption(QNativeSocketEngine::SocketOption opt
bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16 port)
{
#ifdef QNATIVESOCKETENGINE_DEBUG
- qDebug("QNativeSocketEnginePrivate::nativeConnect() : %lli", socketDescriptor);
+ qDebug() << "QNativeSocketEnginePrivate::nativeConnect() " << socketDescriptor;
#endif
struct sockaddr_in sockAddrIPv4;
@@ -405,6 +417,9 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
}
int connectResult = qt_safe_connect(socketDescriptor, sockAddrPtr, sockAddrSize);
+#if defined (QNATIVESOCKETENGINE_DEBUG)
+ int ecopy = errno;
+#endif
if (connectResult == -1) {
switch (errno) {
case EISCONN:
@@ -456,7 +471,7 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16
qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
addr.toString().toLatin1().constData(), port,
socketState == QAbstractSocket::ConnectingState
- ? "Connection in progress" : socketErrorString.toLatin1().constData());
+ ? "Connection in progress" : strerror(ecopy));
#endif
return false;
}
@@ -524,6 +539,9 @@ bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16
}
if (bindResult < 0) {
+#if defined (QNATIVESOCKETENGINE_DEBUG)
+ int ecopy = errno;
+#endif
switch(errno) {
case EADDRINUSE:
setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
@@ -543,7 +561,7 @@ bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
- address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
+ address.toString().toLatin1().constData(), port, strerror(ecopy));
#endif
return false;
@@ -563,6 +581,9 @@ bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16
bool QNativeSocketEnginePrivate::nativeListen(int backlog)
{
if (qt_safe_listen(socketDescriptor, backlog) < 0) {
+#if defined (QNATIVESOCKETENGINE_DEBUG)
+ int ecopy = errno;
+#endif
switch (errno) {
case EADDRINUSE:
setError(QAbstractSocket::AddressInUseError,
@@ -574,7 +595,7 @@ bool QNativeSocketEnginePrivate::nativeListen(int backlog)
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == false (%s)",
- backlog, socketErrorString.toLatin1().constData());
+ backlog, strerror(ecopy));
#endif
return false;
}
diff --git a/src/network/socket/qnativesocketengine_winrt.cpp b/src/network/socket/qnativesocketengine_winrt.cpp
index 1646940cb8..4825d223ee 100644
--- a/src/network/socket/qnativesocketengine_winrt.cpp
+++ b/src/network/socket/qnativesocketengine_winrt.cpp
@@ -51,8 +51,14 @@
#include <qelapsedtimer.h>
#include <qthread.h>
#include <qabstracteventdispatcher.h>
+#include <qfunctions_winrt.h>
-#include <private/qeventdispatcher_winrt_p.h>
+#include <private/qthread_p.h>
+#include <private/qabstractsocket_p.h>
+
+#ifndef QT_NO_SSL
+#include <QSslSocket>
+#endif
#include <wrl.h>
#include <windows.foundation.collections.h>
@@ -124,6 +130,20 @@ struct SocketHandler
Q_GLOBAL_STATIC(SocketHandler, gSocketHandler)
+struct SocketGlobal
+{
+ SocketGlobal()
+ {
+ HRESULT hr;
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Storage_Streams_Buffer).Get(),
+ &bufferFactory);
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+
+ ComPtr<IBufferFactory> bufferFactory;
+};
+Q_GLOBAL_STATIC(SocketGlobal, g)
+
static inline QString qt_QStringFromHString(const HString &string)
{
UINT32 length;
@@ -131,60 +151,7 @@ static inline QString qt_QStringFromHString(const HString &string)
return QString::fromWCharArray(rawString, length);
}
-#define READ_BUFFER_SIZE 8192
-
-class ByteArrayBuffer : public Microsoft::WRL::RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>,
- IBuffer, Windows::Storage::Streams::IBufferByteAccess>
-{
-public:
- ByteArrayBuffer(int size) : m_bytes(size, Qt::Uninitialized), m_length(0)
- {
- }
-
- ByteArrayBuffer(const char *data, int size) : m_bytes(data, size), m_length(size)
- {
- }
-
- HRESULT __stdcall Buffer(byte **value)
- {
- *value = reinterpret_cast<byte *>(m_bytes.data());
- return S_OK;
- }
-
- HRESULT __stdcall get_Capacity(UINT32 *value)
- {
- *value = m_bytes.size();
- return S_OK;
- }
-
- HRESULT __stdcall get_Length(UINT32 *value)
- {
- *value = m_length;
- return S_OK;
- }
-
- HRESULT __stdcall put_Length(UINT32 value)
- {
- Q_ASSERT(value <= UINT32(m_bytes.size()));
- m_length = value;
- return S_OK;
- }
-
- ComPtr<IInputStream> inputStream() const
- {
- return m_stream;
- }
-
- void setInputStream(ComPtr<IInputStream> stream)
- {
- m_stream = stream;
- }
-
-private:
- QByteArray m_bytes;
- UINT32 m_length;
- ComPtr<IInputStream> m_stream;
-};
+#define READ_BUFFER_SIZE 65536
template <typename T>
static AsyncStatus opStatus(const ComPtr<T> &op)
@@ -207,6 +174,12 @@ static AsyncStatus opStatus(const ComPtr<T> &op)
QNativeSocketEngine::QNativeSocketEngine(QObject *parent)
: QAbstractSocketEngine(*new QNativeSocketEnginePrivate(), parent)
{
+#ifndef QT_NO_SSL
+ Q_D(QNativeSocketEngine);
+ if (parent)
+ d->sslSocket = qobject_cast<QSslSocket *>(parent->parent());
+#endif
+
connect(this, SIGNAL(connectionReady()), SLOT(connectionNotification()), Qt::QueuedConnection);
connect(this, SIGNAL(readReady()), SLOT(readNotification()), Qt::QueuedConnection);
connect(this, SIGNAL(writeReady()), SLOT(writeNotification()), Qt::QueuedConnection);
@@ -239,16 +212,14 @@ bool QNativeSocketEngine::initialize(qintptr socketDescriptor, QAbstractSocket::
if (isValid())
close();
- d->socketDescriptor = socketDescriptor;
-
// Currently, only TCP sockets are initialized this way.
- SocketHandler *handler = gSocketHandler();
- d->tcp = handler->pendingTcpSockets.take(socketDescriptor);
+ d->socketDescriptor = qintptr(gSocketHandler->pendingTcpSockets.take(socketDescriptor));
d->socketType = QAbstractSocket::TcpSocket;
- if (!d->tcp || !d->fetchConnectionParameters()) {
+ if (!d->socketDescriptor || !d->fetchConnectionParameters()) {
d->setError(QAbstractSocket::UnsupportedSocketOperationError,
d->InvalidSocketErrorString);
+ d->socketDescriptor = -1;
return false;
}
@@ -287,68 +258,23 @@ bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port)
return false;
}
- ComPtr<IAsyncAction> op;
const QString portString = QString::number(port);
HStringReference portReference(reinterpret_cast<LPCWSTR>(portString.utf16()));
HRESULT hr = E_FAIL;
if (d->socketType == QAbstractSocket::TcpSocket)
- hr = d->tcp->ConnectAsync(remoteHost.Get(), portReference.Get(), &op);
+ hr = d->tcpSocket()->ConnectAsync(remoteHost.Get(), portReference.Get(), &d->connectOp);
else if (d->socketType == QAbstractSocket::UdpSocket)
- hr = d->udp->ConnectAsync(remoteHost.Get(), portReference.Get(), &op);
+ hr = d->udpSocket()->ConnectAsync(remoteHost.Get(), portReference.Get(), &d->connectOp);
if (FAILED(hr)) {
qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not obtain connect action");
return false;
}
-
- hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(
- d, &QNativeSocketEnginePrivate::handleConnectToHost).Get());
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Unable to set host connection callback.");
- return false;
- }
d->socketState = QAbstractSocket::ConnectingState;
- while (opStatus(op) == Started)
- d->eventLoop.processEvents();
+ hr = d->connectOp->put_Completed(Callback<IAsyncActionCompletedHandler>(
+ d, &QNativeSocketEnginePrivate::handleConnectToHost).Get());
+ Q_ASSERT_SUCCEEDED(hr);
- AsyncStatus status = opStatus(op);
- if (status == Error || status == Canceled)
- return false;
-
- if (hr == 0x8007274c) { // A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
- d->setError(QAbstractSocket::NetworkError, d->ConnectionTimeOutErrorString);
- d->socketState = QAbstractSocket::UnconnectedState;
- return false;
- }
- if (hr == 0x8007274d) { // No connection could be made because the target machine actively refused it.
- d->setError(QAbstractSocket::ConnectionRefusedError, d->ConnectionRefusedErrorString);
- d->socketState = QAbstractSocket::UnconnectedState;
- return false;
- }
- if (FAILED(hr)) {
- d->setError(QAbstractSocket::UnknownSocketError, d->UnknownSocketErrorString);
- d->socketState = QAbstractSocket::UnconnectedState;
- return false;
- }
-
- if (d->socketType == QAbstractSocket::TcpSocket) {
- IInputStream *stream;
- hr = d->tcp->get_InputStream(&stream);
- if (FAILED(hr))
- return false;
- ByteArrayBuffer *buffer = static_cast<ByteArrayBuffer *>(d->readBuffer.Get());
- buffer->setInputStream(stream);
- ComPtr<IAsyncBufferOperation> op;
- hr = stream->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
- if (FAILED(hr))
- return false;
- hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get());
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to set socket read callback.");
- return false;
- }
- }
- d->socketState = QAbstractSocket::ConnectedState;
- return true;
+ return d->socketState == QAbstractSocket::ConnectedState;
}
bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
@@ -385,7 +311,7 @@ bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
return false;
}
} else if (d->socketType == QAbstractSocket::UdpSocket) {
- hr = d->udp->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op);
+ hr = d->udpSocket()->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message
return false;
@@ -447,13 +373,16 @@ int QNativeSocketEngine::accept()
if (d->socketType == QAbstractSocket::TcpSocket) {
IStreamSocket *socket = d->pendingConnections.takeFirst();
- IInputStream *stream;
- socket->get_InputStream(&stream);
- // TODO: delete buffer and stream on socket close
- ByteArrayBuffer *buffer = static_cast<ByteArrayBuffer *>(d->readBuffer.Get());
- buffer->setInputStream(stream);
+ HRESULT hr;
+ ComPtr<IBuffer> buffer;
+ hr = g->bufferFactory->Create(READ_BUFFER_SIZE, &buffer);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<IInputStream> stream;
+ hr = socket->get_InputStream(&stream);
+ Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncBufferOperation> op;
- HRESULT hr = stream->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
+ hr = stream->ReadAsync(buffer.Get(), READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Faild to read from the socket buffer.");
return -1;
@@ -476,17 +405,29 @@ int QNativeSocketEngine::accept()
void QNativeSocketEngine::close()
{
Q_D(QNativeSocketEngine);
+
+ if (d->connectOp) {
+ ComPtr<IAsyncInfo> info;
+ d->connectOp.As(&info);
+ if (info) {
+ info->Cancel();
+ info->Close();
+ }
+ }
+
if (d->socketDescriptor != -1) {
- IClosable *socket = 0;
- if (d->socketType == QAbstractSocket::TcpSocket && d->tcp)
- d->tcp->QueryInterface(IID_PPV_ARGS(&socket));
- else if (d->socketType == QAbstractSocket::UdpSocket && d->udp)
- d->udp->QueryInterface(IID_PPV_ARGS(&socket));
+ ComPtr<IClosable> socket;
+ if (d->socketType == QAbstractSocket::TcpSocket) {
+ d->tcpSocket()->QueryInterface(IID_PPV_ARGS(&socket));
+ d->tcpSocket()->Release();
+ } else if (d->socketType == QAbstractSocket::UdpSocket) {
+ d->udpSocket()->QueryInterface(IID_PPV_ARGS(&socket));
+ d->udpSocket()->Release();
+ }
if (socket) {
d->closingDown = true;
socket->Close();
- socket->Release();
d->socketDescriptor = -1;
}
d->socketDescriptor = -1;
@@ -550,42 +491,40 @@ qint64 QNativeSocketEngine::read(char *data, qint64 maxlen)
qint64 QNativeSocketEngine::write(const char *data, qint64 len)
{
Q_D(QNativeSocketEngine);
+ if (!isValid())
+ return -1;
+
HRESULT hr = E_FAIL;
ComPtr<IOutputStream> stream;
if (d->socketType == QAbstractSocket::TcpSocket)
- hr = d->tcp->get_OutputStream(&stream);
+ hr = d->tcpSocket()->get_OutputStream(&stream);
else if (d->socketType == QAbstractSocket::UdpSocket)
- hr = d->udp->get_OutputStream(&stream);
+ hr = d->udpSocket()->get_OutputStream(&stream);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get output stream to socket.");
return -1;
}
- ComPtr<ByteArrayBuffer> buffer = Make<ByteArrayBuffer>(data, len);
+ ComPtr<IBuffer> buffer;
+ hr = g->bufferFactory->Create(len, &buffer);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = buffer->put_Length(len);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<Windows::Storage::Streams::IBufferByteAccess> byteArrayAccess;
+ hr = buffer.As(&byteArrayAccess);
+ Q_ASSERT_SUCCEEDED(hr);
+ byte *bytes;
+ hr = byteArrayAccess->Buffer(&bytes);
+ Q_ASSERT_SUCCEEDED(hr);
+ memcpy(bytes, data, len);
ComPtr<IAsyncOperationWithProgress<UINT32, UINT32>> op;
hr = stream->WriteAsync(buffer.Get(), &op);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to write to socket.");
- return -1;
- }
- hr = op->put_Completed(Callback<IAsyncOperationWithProgressCompletedHandler<UINT32, UINT32>>(
- d, &QNativeSocketEnginePrivate::handleWriteCompleted).Get());
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to set socket write callback.");
- return -1;
- }
-
- while (opStatus(op) == Started)
- d->eventLoop.processEvents();
-
- AsyncStatus status = opStatus(op);
- if (status == Error || status == Canceled)
- return -1;
+ RETURN_IF_FAILED("Failed to write to stream", return -1);
UINT32 bytesWritten;
- hr = op->GetResults(&bytesWritten);
+ hr = QWinRTFunctions::await(op, &bytesWritten);
if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to get written socket length.");
+ d->setError(QAbstractSocket::SocketAccessError, QNativeSocketEnginePrivate::AccessErrorString);
return -1;
}
@@ -624,11 +563,10 @@ qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress
*addr = returnAddress;
*port = returnPort;
arg = d->pendingDatagrams.takeFirst();
+ arg->Release();
// TODO: fill data
Q_UNUSED(data);
- arg->Release();
- delete arg;
--i;
return maxlen;
}
@@ -657,7 +595,7 @@ qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QH
ComPtr<IOutputStream> stream;
const QString portString = QString::number(port);
HStringReference portRef(reinterpret_cast<LPCWSTR>(portString.utf16()));
- if (FAILED(d->udp->GetOutputStreamAsync(remoteHost.Get(), portRef.Get(), &streamOperation)))
+ if (FAILED(d->udpSocket()->GetOutputStreamAsync(remoteHost.Get(), portRef.Get(), &streamOperation)))
return -1;
HRESULT hr;
while (hr = streamOperation->GetResults(&stream) == E_ILLEGAL_METHOD_CALL)
@@ -827,29 +765,50 @@ void QNativeSocketEngine::setExceptionNotificationEnabled(bool enable)
d->notifyOnException = enable;
}
+void QNativeSocketEngine::establishRead()
+{
+ Q_D(QNativeSocketEngine);
+
+ HRESULT hr;
+ ComPtr<IInputStream> stream;
+ hr = d->tcpSocket()->get_InputStream(&stream);
+ RETURN_VOID_IF_FAILED("Failed to get socket input stream");
+
+ ComPtr<IBuffer> buffer;
+ hr = g->bufferFactory->Create(READ_BUFFER_SIZE, &buffer);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<IAsyncBufferOperation> op;
+ hr = stream->ReadAsync(buffer.Get(), READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
+ RETURN_VOID_IF_FAILED("Failed to initiate socket read");
+ hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get());
+ Q_ASSERT_SUCCEEDED(hr);
+}
+
bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
{
Q_UNUSED(socketProtocol);
- SocketHandler *handler = gSocketHandler();
switch (socketType) {
case QAbstractSocket::TcpSocket: {
- if (FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocket).Get(),
- reinterpret_cast<IInspectable **>(&tcp)))) {
+ ComPtr<IStreamSocket> socket;
+ HRESULT hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocket).Get(), &socket);
+ if (FAILED(hr)) {
qWarning("Failed to create StreamSocket instance");
return false;
}
- socketDescriptor = ++handler->socketCount;
+ socketDescriptor = qintptr(socket.Detach());
return true;
}
case QAbstractSocket::UdpSocket: {
- if (FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(),
- reinterpret_cast<IInspectable **>(&udp)))) {
+ ComPtr<IDatagramSocket> socket;
+ HRESULT hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &socket);
+ if (FAILED(hr)) {
qWarning("Failed to create stream socket");
return false;
}
EventRegistrationToken token;
- udp->add_MessageReceived(Callback<DatagramReceivedHandler>(this, &QNativeSocketEnginePrivate::handleNewDatagram).Get(), &token);
- socketDescriptor = ++handler->socketCount;
+ socketDescriptor = qintptr(socket.Detach());
+ udpSocket()->add_MessageReceived(Callback<DatagramReceivedHandler>(this, &QNativeSocketEnginePrivate::handleNewDatagram).Get(), &token);
return true;
}
default:
@@ -866,9 +825,8 @@ QNativeSocketEnginePrivate::QNativeSocketEnginePrivate()
, notifyOnException(false)
, closingDown(false)
, socketDescriptor(-1)
+ , sslSocket(Q_NULLPTR)
{
- ComPtr<ByteArrayBuffer> buffer = Make<ByteArrayBuffer>(READ_BUFFER_SIZE);
- readBuffer = buffer;
}
QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate()
@@ -982,7 +940,7 @@ int QNativeSocketEnginePrivate::option(QAbstractSocketEngine::SocketOption opt)
{
ComPtr<IStreamSocketControl> control;
if (socketType == QAbstractSocket::TcpSocket) {
- if (FAILED(tcp->get_Control(&control))) {
+ if (FAILED(tcpSocket()->get_Control(&control))) {
qWarning("QNativeSocketEnginePrivate::option: Could not obtain socket control");
return -1;
}
@@ -1038,7 +996,7 @@ bool QNativeSocketEnginePrivate::setOption(QAbstractSocketEngine::SocketOption o
{
ComPtr<IStreamSocketControl> control;
if (socketType == QAbstractSocket::TcpSocket) {
- if (FAILED(tcp->get_Control(&control))) {
+ if (FAILED(tcpSocket()->get_Control(&control))) {
qWarning("QNativeSocketEnginePrivate::setOption: Could not obtain socket control");
return false;
}
@@ -1102,7 +1060,7 @@ bool QNativeSocketEnginePrivate::fetchConnectionParameters()
ComPtr<IHostName> hostName;
HString tmpHString;
ComPtr<IStreamSocketInformation> info;
- if (FAILED(tcp->get_Information(&info))) {
+ if (FAILED(tcpSocket()->get_Information(&info))) {
qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket info");
return false;
}
@@ -1131,7 +1089,7 @@ bool QNativeSocketEnginePrivate::fetchConnectionParameters()
ComPtr<IHostName> hostName;
HString tmpHString;
ComPtr<IDatagramSocketInformation> info;
- if (FAILED(udp->get_Information(&info))) {
+ if (FAILED(udpSocket()->get_Information(&info))) {
qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket information");
return false;
}
@@ -1171,8 +1129,46 @@ HRESULT QNativeSocketEnginePrivate::handleClientConnection(IStreamSocketListener
return S_OK;
}
-HRESULT QNativeSocketEnginePrivate::handleConnectToHost(ABI::Windows::Foundation::IAsyncAction *, ABI::Windows::Foundation::AsyncStatus)
+HRESULT QNativeSocketEnginePrivate::handleConnectToHost(IAsyncAction *action, AsyncStatus)
{
+ Q_Q(QNativeSocketEngine);
+
+ HRESULT hr = action->GetResults();
+ if (wasDeleted || !connectOp) // Protect against a late callback
+ return S_OK;
+
+ connectOp.Reset();
+ switch (hr) {
+ case 0x8007274c: // A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
+ setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
+ socketState = QAbstractSocket::UnconnectedState;
+ return S_OK;
+ case 0x80072751: // A socket operation was attempted to an unreachable host.
+ setError(QAbstractSocket::HostNotFoundError, HostUnreachableErrorString);
+ socketState = QAbstractSocket::UnconnectedState;
+ return S_OK;
+ case 0x8007274d: // No connection could be made because the target machine actively refused it.
+ setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
+ socketState = QAbstractSocket::UnconnectedState;
+ return S_OK;
+ default:
+ if (FAILED(hr)) {
+ setError(QAbstractSocket::UnknownSocketError, UnknownSocketErrorString);
+ socketState = QAbstractSocket::UnconnectedState;
+ return S_OK;
+ }
+ break;
+ }
+
+ socketState = QAbstractSocket::ConnectedState;
+ emit q->connectionReady();
+
+ // Delay the reader so that the SSL socket can upgrade
+ if (sslSocket)
+ q->connect(sslSocket, SIGNAL(encrypted()), SLOT(establishRead()));
+ else
+ q->establishRead();
+
return S_OK;
}
@@ -1185,22 +1181,25 @@ HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *async
if (status == Error || status == Canceled)
return S_OK;
- ByteArrayBuffer *buffer = 0;
- HRESULT hr = asyncInfo->GetResults((IBuffer **)&buffer);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to get ready read results.");
- return S_OK;
- }
- UINT32 len;
- buffer->get_Length(&len);
- if (!len) {
+ ComPtr<IBuffer> buffer;
+ HRESULT hr = asyncInfo->GetResults(&buffer);
+ RETURN_OK_IF_FAILED("Failed to get read results buffer");
+
+ UINT32 bufferLength;
+ hr = buffer->get_Length(&bufferLength);
+ Q_ASSERT_SUCCEEDED(hr);
+ if (!bufferLength) {
if (q->isReadNotificationEnabled())
emit q->readReady();
return S_OK;
}
+ ComPtr<Windows::Storage::Streams::IBufferByteAccess> byteArrayAccess;
+ hr = buffer.As(&byteArrayAccess);
+ Q_ASSERT_SUCCEEDED(hr);
byte *data;
- buffer->Buffer(&data);
+ hr = byteArrayAccess->Buffer(&data);
+ Q_ASSERT_SUCCEEDED(hr);
readMutex.lock();
if (readBytes.atEnd()) // Everything has been read; the buffer is safe to reset
@@ -1210,15 +1209,25 @@ HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *async
qint64 readPos = readBytes.pos();
readBytes.seek(readBytes.size());
Q_ASSERT(readBytes.atEnd());
- readBytes.write(reinterpret_cast<const char*>(data), qint64(len));
+ readBytes.write(reinterpret_cast<const char*>(data), qint64(bufferLength));
readBytes.seek(readPos);
readMutex.unlock();
if (q->isReadNotificationEnabled())
emit q->readReady();
+ ComPtr<IInputStream> stream;
+ hr = tcpSocket()->get_InputStream(&stream);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ // Reuse the stream buffer
+ hr = buffer->get_Capacity(&bufferLength);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = buffer->put_Length(0);
+ Q_ASSERT_SUCCEEDED(hr);
+
ComPtr<IAsyncBufferOperation> op;
- hr = buffer->inputStream()->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
+ hr = stream->ReadAsync(buffer.Get(), bufferLength, InputStreamOptions_Partial, &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Could not read into socket stream buffer.");
return S_OK;
@@ -1231,32 +1240,10 @@ HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *async
return S_OK;
}
-HRESULT QNativeSocketEnginePrivate::handleWriteCompleted(IAsyncOperationWithProgress<UINT32, UINT32> *op, AsyncStatus status)
-{
- if (status == Error) {
- ComPtr<IAsyncInfo> info;
- HRESULT hr = op->QueryInterface(IID_PPV_ARGS(&info));
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to cast operation.");
- return S_OK;
- }
- HRESULT errorCode;
- hr = info->get_ErrorCode(&errorCode);
- if (FAILED(hr)) {
- qErrnoWarning(hr, "Failed to get error code.");
- return S_OK;
- }
- qErrnoWarning(errorCode, "A socket error occurred.");
- return S_OK;
- }
-
- return S_OK;
-}
-
HRESULT QNativeSocketEnginePrivate::handleNewDatagram(IDatagramSocket *socket, IDatagramSocketMessageReceivedEventArgs *args)
{
Q_Q(QNativeSocketEngine);
- Q_UNUSED(socket)
+ Q_UNUSED(socket);
pendingDatagrams.append(args);
emit q->readReady();
diff --git a/src/network/socket/qnativesocketengine_winrt_p.h b/src/network/socket/qnativesocketengine_winrt_p.h
index ec2e1b3ad4..1d84c93f0a 100644
--- a/src/network/socket/qnativesocketengine_winrt_p.h
+++ b/src/network/socket/qnativesocketengine_winrt_p.h
@@ -134,6 +134,9 @@ signals:
void readReady();
void writeReady();
+private slots:
+ void establishRead();
+
private:
Q_DECLARE_PRIVATE(QNativeSocketEngine)
Q_DISABLE_COPY(QNativeSocketEngine)
@@ -192,19 +195,21 @@ public:
bool checkProxy(const QHostAddress &address);
bool fetchConnectionParameters();
+
private:
- union {
- ABI::Windows::Networking::Sockets::IStreamSocket *tcp;
- ABI::Windows::Networking::Sockets::IDatagramSocket *udp;
- };
+ inline ABI::Windows::Networking::Sockets::IStreamSocket *tcpSocket() const
+ { return reinterpret_cast<ABI::Windows::Networking::Sockets::IStreamSocket *>(socketDescriptor); }
+ inline ABI::Windows::Networking::Sockets::IDatagramSocket *udpSocket() const
+ { return reinterpret_cast<ABI::Windows::Networking::Sockets::IDatagramSocket *>(socketDescriptor); }
Microsoft::WRL::ComPtr<ABI::Windows::Networking::Sockets::IStreamSocketListener> tcpListener;
- Microsoft::WRL::ComPtr<ABI::Windows::Storage::Streams::IBuffer> readBuffer;
+ Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncAction> connectOp;
QBuffer readBytes;
QMutex readMutex;
QList<ABI::Windows::Networking::Sockets::IDatagramSocketMessageReceivedEventArgs *> pendingDatagrams;
QList<ABI::Windows::Networking::Sockets::IStreamSocket *> pendingConnections;
QList<ABI::Windows::Networking::Sockets::IStreamSocket *> currentConnections;
QEventLoop eventLoop;
+ QAbstractSocket *sslSocket;
HRESULT handleBindCompleted(ABI::Windows::Foundation::IAsyncAction *, ABI::Windows::Foundation::AsyncStatus);
HRESULT handleNewDatagram(ABI::Windows::Networking::Sockets::IDatagramSocket *socket,
@@ -213,7 +218,6 @@ private:
ABI::Windows::Networking::Sockets::IStreamSocketListenerConnectionReceivedEventArgs *args);
HRESULT handleConnectToHost(ABI::Windows::Foundation::IAsyncAction *, ABI::Windows::Foundation::AsyncStatus);
HRESULT handleReadyRead(ABI::Windows::Foundation::IAsyncOperationWithProgress<ABI::Windows::Storage::Streams::IBuffer *, UINT32> *asyncInfo, ABI::Windows::Foundation::AsyncStatus);
- HRESULT handleWriteCompleted(ABI::Windows::Foundation::IAsyncOperationWithProgress<UINT32, UINT32> *, ABI::Windows::Foundation::AsyncStatus);
};
QT_END_NAMESPACE
diff --git a/src/network/ssl/qasn1element.cpp b/src/network/ssl/qasn1element.cpp
new file mode 100644
index 0000000000..f3f280d863
--- /dev/null
+++ b/src/network/ssl/qasn1element.cpp
@@ -0,0 +1,346 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Jeremy Lainé <jeremy.laine@m4x.org>
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qasn1element_p.h"
+
+#include <QtCore/qdatastream.h>
+#include <QtCore/qdatetime.h>
+#include <QtCore/qvector.h>
+#include <QDebug>
+
+QT_BEGIN_NAMESPACE
+
+typedef QMap<QByteArray, QByteArray> OidNameMap;
+static OidNameMap createOidMap()
+{
+ OidNameMap oids;
+ // used by unit tests
+ oids.insert(oids.end(), QByteArrayLiteral("0.9.2342.19200300.100.1.5"), QByteArrayLiteral("favouriteDrink"));
+ oids.insert(oids.end(), QByteArrayLiteral("1.2.840.113549.1.9.1"), QByteArrayLiteral("emailAddress"));
+ oids.insert(oids.end(), QByteArrayLiteral("1.3.6.1.5.5.7.1.1"), QByteArrayLiteral("authorityInfoAccess"));
+ oids.insert(oids.end(), QByteArrayLiteral("1.3.6.1.5.5.7.48.1"), QByteArrayLiteral("OCSP"));
+ oids.insert(oids.end(), QByteArrayLiteral("1.3.6.1.5.5.7.48.2"), QByteArrayLiteral("caIssuers"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.29.14"), QByteArrayLiteral("subjectKeyIdentifier"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.29.15"), QByteArrayLiteral("keyUsage"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.29.17"), QByteArrayLiteral("subjectAltName"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.29.19"), QByteArrayLiteral("basicConstraints"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.29.35"), QByteArrayLiteral("authorityKeyIdentifier"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.10"), QByteArrayLiteral("O"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.11"), QByteArrayLiteral("OU"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.12"), QByteArrayLiteral("title"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.13"), QByteArrayLiteral("description"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.17"), QByteArrayLiteral("postalCode"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.3"), QByteArrayLiteral("CN"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.4"), QByteArrayLiteral("SN"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.41"), QByteArrayLiteral("name"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.42"), QByteArrayLiteral("GN"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.43"), QByteArrayLiteral("initials"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.46"), QByteArrayLiteral("dnQualifier"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.5"), QByteArrayLiteral("serialNumber"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.6"), QByteArrayLiteral("C"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.7"), QByteArrayLiteral("L"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.8"), QByteArrayLiteral("ST"));
+ oids.insert(oids.end(), QByteArrayLiteral("2.5.4.9"), QByteArrayLiteral("street"));
+ return oids;
+}
+Q_GLOBAL_STATIC_WITH_ARGS(OidNameMap, oidNameMap, (createOidMap()))
+
+QAsn1Element::QAsn1Element(quint8 type, const QByteArray &value)
+ : mType(type)
+ , mValue(value)
+{
+}
+
+bool QAsn1Element::read(QDataStream &stream)
+{
+ // type
+ quint8 tmpType;
+ stream >> tmpType;
+ if (!tmpType)
+ return false;
+
+ // length
+ qint64 length = 0;
+ quint8 first;
+ stream >> first;
+ if (first & 0x80) {
+ // long form
+ const quint8 bytes = (first & 0x7f);
+ if (bytes > 7)
+ return false;
+
+ quint8 b;
+ for (int i = 0; i < bytes; i++) {
+ stream >> b;
+ length = (length << 8) | b;
+ }
+ } else {
+ // short form
+ length = (first & 0x7f);
+ }
+
+ // value
+ QByteArray tmpValue;
+ tmpValue.resize(length);
+ int count = stream.readRawData(tmpValue.data(), tmpValue.size());
+ if (count != length)
+ return false;
+
+ mType = tmpType;
+ mValue.swap(tmpValue);
+ return true;
+}
+
+bool QAsn1Element::read(const QByteArray &data)
+{
+ QDataStream stream(data);
+ return read(stream);
+}
+
+void QAsn1Element::write(QDataStream &stream) const
+{
+ // type
+ stream << mType;
+
+ // length
+ qint64 length = mValue.size();
+ if (length >= 128) {
+ // long form
+ quint8 encodedLength = 0x80;
+ QByteArray ba;
+ while (length) {
+ ba.prepend(quint8((length & 0xff)));
+ length >>= 8;
+ encodedLength += 1;
+ }
+ stream << encodedLength;
+ stream.writeRawData(ba.data(), ba.size());
+ } else {
+ // short form
+ stream << quint8(length);
+ }
+
+ // value
+ stream.writeRawData(mValue.data(), mValue.size());
+}
+
+QAsn1Element QAsn1Element::fromBool(bool val)
+{
+ return QAsn1Element(QAsn1Element::BooleanType,
+ QByteArray(1, val ? 0xff : 0x00));
+}
+
+QAsn1Element QAsn1Element::fromInteger(unsigned int val)
+{
+ QAsn1Element elem(QAsn1Element::IntegerType);
+ while (val > 127) {
+ elem.mValue.prepend(val & 0xff);
+ val >>= 8;
+ }
+ elem.mValue.prepend(val & 0x7f);
+ return elem;
+}
+
+QAsn1Element QAsn1Element::fromVector(const QVector<QAsn1Element> &items)
+{
+ QAsn1Element seq;
+ seq.mType = SequenceType;
+ QDataStream stream(&seq.mValue, QIODevice::WriteOnly);
+ for (QVector<QAsn1Element>::const_iterator it = items.cbegin(), end = items.cend(); it != end; ++it)
+ it->write(stream);
+ return seq;
+}
+
+QAsn1Element QAsn1Element::fromObjectId(const QByteArray &id)
+{
+ QAsn1Element elem;
+ elem.mType = ObjectIdentifierType;
+ QList<QByteArray> bits = id.split('.');
+ Q_ASSERT(bits.size() > 2);
+ elem.mValue += quint8((bits[0].toUInt() * 40 + bits[1].toUInt()));
+ for (int i = 2; i < bits.size(); ++i) {
+ char buffer[std::numeric_limits<unsigned int>::digits / 7 + 2];
+ char *pBuffer = buffer + sizeof(buffer);
+ *--pBuffer = '\0';
+ unsigned int node = bits[i].toUInt();
+ *--pBuffer = quint8((node & 0x7f));
+ node >>= 7;
+ while (node) {
+ *--pBuffer = quint8(((node & 0x7f) | 0x80));
+ node >>= 7;
+ }
+ elem.mValue += pBuffer;
+ }
+ return elem;
+}
+
+bool QAsn1Element::toBool(bool *ok) const
+{
+ if (*this == fromBool(true)) {
+ if (ok)
+ *ok = true;
+ return true;
+ } else if (*this == fromBool(false)) {
+ if (ok)
+ *ok = true;
+ return false;
+ } else {
+ if (ok)
+ *ok = false;
+ return false;
+ }
+}
+
+QDateTime QAsn1Element::toDateTime() const
+{
+ if (mValue.endsWith('Z')) {
+ if (mType == UtcTimeType && mValue.size() == 13)
+ return QDateTime(QDate(2000 + mValue.mid(0, 2).toInt(),
+ mValue.mid(2, 2).toInt(),
+ mValue.mid(4, 2).toInt()),
+ QTime(mValue.mid(6, 2).toInt(),
+ mValue.mid(8, 2).toInt(),
+ mValue.mid(10, 2).toInt()),
+ Qt::UTC);
+ else if (mType == GeneralizedTimeType && mValue.size() == 15)
+ return QDateTime(QDate(mValue.mid(0, 4).toInt(),
+ mValue.mid(4, 2).toInt(),
+ mValue.mid(6, 2).toInt()),
+ QTime(mValue.mid(8, 2).toInt(),
+ mValue.mid(10, 2).toInt(),
+ mValue.mid(12, 2).toInt()),
+ Qt::UTC);
+ }
+ return QDateTime();
+}
+
+QMultiMap<QByteArray, QString> QAsn1Element::toInfo() const
+{
+ QMultiMap<QByteArray, QString> info;
+ QAsn1Element elem;
+ QDataStream issuerStream(mValue);
+ while (elem.read(issuerStream) && elem.mType == QAsn1Element::SetType) {
+ QAsn1Element issuerElem;
+ QDataStream setStream(elem.mValue);
+ if (issuerElem.read(setStream) && issuerElem.mType == QAsn1Element::SequenceType) {
+ QVector<QAsn1Element> elems = issuerElem.toVector();
+ if (elems.size() == 2) {
+ const QByteArray key = elems.front().toObjectName();
+ if (!key.isEmpty())
+ info.insert(key, elems.back().toString());
+ }
+ }
+ }
+ return info;
+}
+
+qint64 QAsn1Element::toInteger(bool *ok) const
+{
+ if (mType != QAsn1Element::IntegerType || mValue.isEmpty()) {
+ if (ok)
+ *ok = false;
+ return 0;
+ }
+
+ // NOTE: negative numbers are not handled
+ if (mValue.at(0) & 0x80) {
+ if (ok)
+ *ok = false;
+ return 0;
+ }
+
+ qint64 value = mValue.at(0) & 0x7f;
+ for (int i = 1; i < mValue.size(); ++i)
+ value = (value << 8) | quint8(mValue.at(i));
+
+ if (ok)
+ *ok = true;
+ return value;
+}
+
+QVector<QAsn1Element> QAsn1Element::toVector() const
+{
+ QVector<QAsn1Element> items;
+ if (mType == SequenceType) {
+ QAsn1Element elem;
+ QDataStream stream(mValue);
+ while (elem.read(stream))
+ items << elem;
+ }
+ return items;
+}
+
+QByteArray QAsn1Element::toObjectId() const
+{
+ QByteArray key;
+ if (mType == ObjectIdentifierType && !mValue.isEmpty()) {
+ quint8 b = mValue[0];
+ key += QByteArray::number(b / 40) + '.' + QByteArray::number (b % 40);
+ unsigned int val = 0;
+ for (int i = 1; i < mValue.size(); ++i) {
+ b = mValue[i];
+ val = (val << 7) | (b & 0x7f);
+ if (!(b & 0x80)) {
+ key += '.' + QByteArray::number(val);
+ val = 0;
+ }
+ }
+ }
+ return key;
+}
+
+QByteArray QAsn1Element::toObjectName() const
+{
+ QByteArray key = toObjectId();
+ return oidNameMap->value(key, key);
+}
+
+QString QAsn1Element::toString() const
+{
+ if (mType == PrintableStringType || mType == TeletexStringType)
+ return QString::fromLatin1(mValue, mValue.size());
+ if (mType == Utf8StringType)
+ return QString::fromUtf8(mValue, mValue.size());
+ return QString();
+}
+
+QT_END_NAMESPACE
diff --git a/src/network/ssl/qasn1element_p.h b/src/network/ssl/qasn1element_p.h
new file mode 100644
index 0000000000..36a7c90de3
--- /dev/null
+++ b/src/network/ssl/qasn1element_p.h
@@ -0,0 +1,128 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Jeremy Lainé <jeremy.laine@m4x.org>
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QASN1ELEMENT_P_H
+#define QASN1ELEMENT_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of the QLibrary class. This header file may change from
+// version to version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtCore/qdatetime.h>
+#include <QtCore/qmap.h>
+
+QT_BEGIN_NAMESPACE
+
+#define RSA_ENCRYPTION_OID QByteArrayLiteral("1.2.840.113549.1.1.1")
+#define DSA_ENCRYPTION_OID QByteArrayLiteral("1.2.840.10040.4.1")
+
+class Q_AUTOTEST_EXPORT QAsn1Element
+{
+public:
+ enum ElementType {
+ // universal
+ BooleanType = 0x01,
+ IntegerType = 0x02,
+ BitStringType = 0x03,
+ OctetStringType = 0x04,
+ NullType = 0x05,
+ ObjectIdentifierType = 0x06,
+ Utf8StringType = 0x0c,
+ PrintableStringType = 0x13,
+ TeletexStringType = 0x14,
+ UtcTimeType = 0x17,
+ GeneralizedTimeType = 0x18,
+ SequenceType = 0x30,
+ SetType = 0x31,
+
+ // context specific
+ Context0Type = 0xA0,
+ Context3Type = 0xA3
+ };
+
+ explicit QAsn1Element(quint8 type = 0, const QByteArray &value = QByteArray());
+ bool read(QDataStream &data);
+ bool read(const QByteArray &data);
+ void write(QDataStream &data) const;
+
+ static QAsn1Element fromBool(bool val);
+ static QAsn1Element fromInteger(unsigned int val);
+ static QAsn1Element fromVector(const QVector<QAsn1Element> &items);
+ static QAsn1Element fromObjectId(const QByteArray &id);
+
+ bool toBool(bool *ok = 0) const;
+ QDateTime toDateTime() const;
+ QMultiMap<QByteArray, QString> toInfo() const;
+ qint64 toInteger(bool *ok = 0) const;
+ QVector<QAsn1Element> toVector() const;
+ QByteArray toObjectId() const;
+ QByteArray toObjectName() const;
+ QString toString() const;
+
+ quint8 type() const { return mType; }
+ QByteArray value() const { return mValue; }
+
+ friend inline bool operator==(const QAsn1Element &, const QAsn1Element &);
+ friend inline bool operator!=(const QAsn1Element &, const QAsn1Element &);
+
+private:
+ quint8 mType;
+ QByteArray mValue;
+};
+Q_DECLARE_TYPEINFO(QAsn1Element, Q_MOVABLE_TYPE);
+
+inline bool operator==(const QAsn1Element &e1, const QAsn1Element &e2)
+{ return e1.mType == e2.mType && e1.mValue == e2.mValue; }
+
+inline bool operator!=(const QAsn1Element &e1, const QAsn1Element &e2)
+{ return e1.mType != e2.mType || e1.mValue != e2.mValue; }
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/network/ssl/qsslcertificate.cpp b/src/network/ssl/qsslcertificate.cpp
index a113ec156b..47ea3343ea 100644
--- a/src/network/ssl/qsslcertificate.cpp
+++ b/src/network/ssl/qsslcertificate.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -113,33 +113,23 @@
\value EmailAddress The email address associated with the certificate
*/
+#ifndef QT_NO_OPENSSL
#include "qsslsocket_openssl_symbols_p.h"
+#endif
+#ifdef Q_OS_WINRT
+#include "qsslsocket_winrt_p.h"
+#endif
+
#include "qsslcertificate.h"
#include "qsslcertificate_p.h"
-#include "qsslkey.h"
#include "qsslkey_p.h"
-#include "qsslcertificateextension.h"
-#include "qsslcertificateextension_p.h"
-#include <QtCore/qatomic.h>
-#include <QtCore/qdatetime.h>
-#include <QtCore/qdebug.h>
#include <QtCore/qdir.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qfile.h>
-#include <QtCore/qfileinfo.h>
-#include <QtCore/qmap.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/private/qmutexpool_p.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qstringlist.h>
-#include <QtCore/qvarlengtharray.h>
QT_BEGIN_NAMESPACE
-// forward declaration
-static QMap<QByteArray, QString> _q_mapFromX509Name(X509_NAME *name);
-
/*!
Constructs a QSslCertificate by reading \a format encoded data
from \a device and using the first certificate found. You can
@@ -200,19 +190,11 @@ QSslCertificate &QSslCertificate::operator=(const QSslCertificate &other)
*/
/*!
+ \fn bool QSslCertificate::operator==(const QSslCertificate &other) const
+
Returns \c true if this certificate is the same as \a other; otherwise
returns \c false.
*/
-bool QSslCertificate::operator==(const QSslCertificate &other) const
-{
- if (d == other.d)
- return true;
- if (d->null && other.d->null)
- return true;
- if (d->x509 && other.d->x509)
- return q_X509_cmp(d->x509, other.d->x509) == 0;
- return false;
-}
/*!
\fn bool QSslCertificate::operator!=(const QSslCertificate &other) const
@@ -222,6 +204,8 @@ bool QSslCertificate::operator==(const QSslCertificate &other) const
*/
/*!
+ \fn bool QSslCertificate::isNull() const
+
Returns \c true if this is a null certificate (i.e., a certificate
with no contents); otherwise returns \c false.
@@ -229,10 +213,6 @@ bool QSslCertificate::operator==(const QSslCertificate &other) const
\sa clear()
*/
-bool QSslCertificate::isNull() const
-{
- return d->null;
-}
#if QT_DEPRECATED_SINCE(5,0)
/*!
@@ -265,6 +245,17 @@ bool QSslCertificate::isBlacklisted() const
}
/*!
+ \fn bool QSslCertificate::isSelfSigned() const
+ \since 5.4
+
+ Returns \c true if this certificate is self signed; otherwise
+ returns \c false.
+
+ A certificate is considered self-signed its issuer and subject
+ are identical.
+*/
+
+/*!
Clears the contents of this certificate, making it a null
certificate.
@@ -278,37 +269,15 @@ void QSslCertificate::clear()
}
/*!
+ \fn QByteArray QSslCertificate::version() const
Returns the certificate's version string.
*/
-QByteArray QSslCertificate::version() const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- if (d->versionString.isEmpty() && d->x509)
- d->versionString =
- QByteArray::number(qlonglong(q_ASN1_INTEGER_get(d->x509->cert_info->version)) + 1);
-
- return d->versionString;
-}
/*!
+ \fn QByteArray QSslCertificate::serialNumber() const
+
Returns the certificate's serial number string in hexadecimal format.
*/
-QByteArray QSslCertificate::serialNumber() const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- if (d->serialNumberString.isEmpty() && d->x509) {
- ASN1_INTEGER *serialNumber = d->x509->cert_info->serialNumber;
- QByteArray hexString;
- hexString.reserve(serialNumber->length * 3);
- for (int a = 0; a < serialNumber->length; ++a) {
- hexString += QByteArray::number(serialNumber->data[a], 16).rightJustified(2, '0');
- hexString += ':';
- }
- hexString.chop(1);
- d->serialNumberString = hexString;
- }
- return d->serialNumberString;
-}
/*!
Returns a cryptographic digest of this certificate. By default,
@@ -320,23 +289,6 @@ QByteArray QSslCertificate::digest(QCryptographicHash::Algorithm algorithm) cons
return QCryptographicHash::hash(toDer(), algorithm);
}
-static QByteArray _q_SubjectInfoToString(QSslCertificate::SubjectInfo info)
-{
- QByteArray str;
- switch (info) {
- case QSslCertificate::Organization: str = QByteArray("O"); break;
- case QSslCertificate::CommonName: str = QByteArray("CN"); break;
- case QSslCertificate::LocalityName: str = QByteArray("L"); break;
- case QSslCertificate::OrganizationalUnitName: str = QByteArray("OU"); break;
- case QSslCertificate::CountryName: str = QByteArray("C"); break;
- case QSslCertificate::StateOrProvinceName: str = QByteArray("ST"); break;
- case QSslCertificate::DistinguishedNameQualifier: str = QByteArray("dnQualifier"); break;
- case QSslCertificate::SerialNumber: str = QByteArray("serialNumber"); break;
- case QSslCertificate::EmailAddress: str = QByteArray("emailAddress"); break;
- }
- return str;
-}
-
/*!
\fn QString QSslCertificate::issuerInfo(SubjectInfo subject) const
@@ -347,37 +299,18 @@ static QByteArray _q_SubjectInfoToString(QSslCertificate::SubjectInfo info)
\sa subjectInfo()
*/
-QStringList QSslCertificate::issuerInfo(SubjectInfo info) const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- // lazy init
- if (d->issuerInfo.isEmpty() && d->x509)
- d->issuerInfo =
- _q_mapFromX509Name(q_X509_get_issuer_name(d->x509));
-
- return d->issuerInfo.values(_q_SubjectInfoToString(info));
-}
/*!
+ \fn QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const
+
Returns the issuer information for \a attribute from the certificate,
or an empty list if there is no information for \a attribute in the
certificate. There can be more than one entry for an attribute.
\sa subjectInfo()
*/
-QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- // lazy init
- if (d->issuerInfo.isEmpty() && d->x509)
- d->issuerInfo =
- _q_mapFromX509Name(q_X509_get_issuer_name(d->x509));
-
- return d->issuerInfo.values(attribute);
-}
/*!
-
\fn QString QSslCertificate::subjectInfo(SubjectInfo subject) const
Returns the information for the \a subject, or an empty list if
@@ -386,36 +319,20 @@ QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const
\sa issuerInfo()
*/
-QStringList QSslCertificate::subjectInfo(SubjectInfo info) const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- // lazy init
- if (d->subjectInfo.isEmpty() && d->x509)
- d->subjectInfo =
- _q_mapFromX509Name(q_X509_get_subject_name(d->x509));
-
- return d->subjectInfo.values(_q_SubjectInfoToString(info));
-}
/*!
+ \fn QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const
+
Returns the subject information for \a attribute, or an empty list if
there is no information for \a attribute in the certificate. There
can be more than one entry for an attribute.
\sa issuerInfo()
*/
-QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- // lazy init
- if (d->subjectInfo.isEmpty() && d->x509)
- d->subjectInfo =
- _q_mapFromX509Name(q_X509_get_subject_name(d->x509));
-
- return d->subjectInfo.values(attribute);
-}
/*!
+ \fn QList<QByteArray> QSslCertificate::subjectInfoAttributes() const
+
\since 5.0
Returns a list of the attributes that have values in the subject
information of this certificate. The information associated
@@ -425,18 +342,10 @@ QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const
\sa subjectInfo()
*/
-QList<QByteArray> QSslCertificate::subjectInfoAttributes() const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- // lazy init
- if (d->subjectInfo.isEmpty() && d->x509)
- d->subjectInfo =
- _q_mapFromX509Name(q_X509_get_subject_name(d->x509));
-
- return d->subjectInfo.uniqueKeys();
-}
/*!
+ \fn QList<QByteArray> QSslCertificate::issuerInfoAttributes() const
+
\since 5.0
Returns a list of the attributes that have values in the issuer
information of this certificate. The information associated
@@ -446,16 +355,6 @@ QList<QByteArray> QSslCertificate::subjectInfoAttributes() const
\sa subjectInfo()
*/
-QList<QByteArray> QSslCertificate::issuerInfoAttributes() const
-{
- QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
- // lazy init
- if (d->issuerInfo.isEmpty() && d->x509)
- d->issuerInfo =
- _q_mapFromX509Name(q_X509_get_issuer_name(d->x509));
-
- return d->issuerInfo.uniqueKeys();
-}
#if QT_DEPRECATED_SINCE(5,0)
/*!
@@ -467,6 +366,8 @@ QList<QByteArray> QSslCertificate::issuerInfoAttributes() const
#endif
/*!
+ \fn QMultiMap<QSsl::AlternativeNameEntryType, QString> QSslCertificate::subjectAlternativeNames() const
+
Returns the list of alternative subject names for this
certificate. The alternative names typically contain host
names, optionally with wildcards, that are valid for this
@@ -479,63 +380,27 @@ QList<QByteArray> QSslCertificate::issuerInfoAttributes() const
\sa subjectInfo()
*/
-QMultiMap<QSsl::AlternativeNameEntryType, QString> QSslCertificate::subjectAlternativeNames() const
-{
- QMultiMap<QSsl::AlternativeNameEntryType, QString> result;
-
- if (!d->x509)
- return result;
-
- STACK_OF(GENERAL_NAME) *altNames = (STACK_OF(GENERAL_NAME)*)q_X509_get_ext_d2i(d->x509, NID_subject_alt_name, 0, 0);
-
- if (altNames) {
- for (int i = 0; i < q_sk_GENERAL_NAME_num(altNames); ++i) {
- const GENERAL_NAME *genName = q_sk_GENERAL_NAME_value(altNames, i);
- if (genName->type != GEN_DNS && genName->type != GEN_EMAIL)
- continue;
-
- int len = q_ASN1_STRING_length(genName->d.ia5);
- if (len < 0 || len >= 8192) {
- // broken name
- continue;
- }
-
- const char *altNameStr = reinterpret_cast<const char *>(q_ASN1_STRING_data(genName->d.ia5));
- const QString altName = QString::fromLatin1(altNameStr, len);
- if (genName->type == GEN_DNS)
- result.insert(QSsl::DnsEntry, altName);
- else if (genName->type == GEN_EMAIL)
- result.insert(QSsl::EmailEntry, altName);
- }
- q_sk_pop_free((STACK*)altNames, reinterpret_cast<void(*)(void*)>(q_sk_free));
- }
-
- return result;
-}
/*!
+ \fn QDateTime QSslCertificate::effectiveDate() const
+
Returns the date-time that the certificate becomes valid, or an
empty QDateTime if this is a null certificate.
\sa expiryDate()
*/
-QDateTime QSslCertificate::effectiveDate() const
-{
- return d->notValidBefore;
-}
/*!
+ \fn QDateTime QSslCertificate::expiryDate() const
+
Returns the date-time that the certificate expires, or an empty
QDateTime if this is a null certificate.
\sa effectiveDate()
*/
-QDateTime QSslCertificate::expiryDate() const
-{
- return d->notValidAfter;
-}
/*!
+ \fn Qt::HANDLE QSslCertificate::handle() const
Returns a pointer to the native certificate handle, if there is
one, or a null pointer otherwise.
@@ -546,298 +411,41 @@ QDateTime QSslCertificate::expiryDate() const
non-portable, and its return value may vary from platform to
platform or change from minor release to minor release.
*/
-Qt::HANDLE QSslCertificate::handle() const
-{
- return Qt::HANDLE(d->x509);
-}
/*!
+ \fn QSslKey QSslCertificate::publicKey() const
Returns the certificate subject's public key.
*/
-QSslKey QSslCertificate::publicKey() const
-{
- if (!d->x509)
- return QSslKey();
-
- QSslKey key;
-
- key.d->type = QSsl::PublicKey;
- X509_PUBKEY *xkey = d->x509->cert_info->key;
- EVP_PKEY *pkey = q_X509_PUBKEY_get(xkey);
- Q_ASSERT(pkey);
-
- if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA) {
- key.d->rsa = q_EVP_PKEY_get1_RSA(pkey);
- key.d->algorithm = QSsl::Rsa;
- key.d->isNull = false;
- } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DSA) {
- key.d->dsa = q_EVP_PKEY_get1_DSA(pkey);
- key.d->algorithm = QSsl::Dsa;
- key.d->isNull = false;
- } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DH) {
- // DH unsupported
- } else {
- // error?
- }
-
- q_EVP_PKEY_free(pkey);
- return key;
-}
-
-/*
- * Convert unknown extensions to a QVariant.
- */
-static QVariant x509UnknownExtensionToValue(X509_EXTENSION *ext)
-{
- // Get the extension specific method object if available
- // we cast away the const-ness here because some versions of openssl
- // don't use const for the parameters in the functions pointers stored
- // in the object.
- X509V3_EXT_METHOD *meth = const_cast<X509V3_EXT_METHOD *>(q_X509V3_EXT_get(ext));
- if (!meth) {
- ASN1_OCTET_STRING *value = q_X509_EXTENSION_get_data(ext);
- QByteArray result( reinterpret_cast<const char *>(q_ASN1_STRING_data(value)),
- q_ASN1_STRING_length(value));
- return result;
- }
-
- //const unsigned char *data = ext->value->data;
- void *ext_internal = q_X509V3_EXT_d2i(ext);
-
- // If this extension can be converted
- if (meth->i2v && ext_internal) {
- STACK_OF(CONF_VALUE) *val = meth->i2v(meth, ext_internal, 0);
-
- QVariantMap map;
- QVariantList list;
- bool isMap = false;
-
- for (int j = 0; j < q_SKM_sk_num(CONF_VALUE, val); j++) {
- CONF_VALUE *nval = q_SKM_sk_value(CONF_VALUE, val, j);
- if (nval->name && nval->value) {
- isMap = true;
- map[QString::fromUtf8(nval->name)] = QString::fromUtf8(nval->value);
- } else if (nval->name) {
- list << QString::fromUtf8(nval->name);
- } else if (nval->value) {
- list << QString::fromUtf8(nval->value);
- }
- }
-
- if (isMap)
- return map;
- else
- return list;
- } else if (meth->i2s && ext_internal) {
- //qDebug() << meth->i2s(meth, ext_internal);
- QVariant result(QString::fromUtf8(meth->i2s(meth, ext_internal)));
- return result;
- } else if (meth->i2r && ext_internal) {
- QByteArray result;
-
- BIO *bio = q_BIO_new(q_BIO_s_mem());
- if (!bio)
- return result;
-
- meth->i2r(meth, ext_internal, bio, 0);
-
- char *bio_buffer;
- long bio_size = q_BIO_get_mem_data(bio, &bio_buffer);
- result = QByteArray(bio_buffer, bio_size);
-
- q_BIO_free(bio);
- return result;
- }
-
- return QVariant();
-}
-
-/*
- * Convert extensions to a variant. The naming of the keys of the map are
- * taken from RFC 5280, however we decided the capitalisation in the RFC
- * was too silly for the real world.
- */
-static QVariant x509ExtensionToValue(X509_EXTENSION *ext)
-{
- ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext);
- int nid = q_OBJ_obj2nid(obj);
-
- switch (nid) {
- case NID_basic_constraints:
- {
- BASIC_CONSTRAINTS *basic = reinterpret_cast<BASIC_CONSTRAINTS *>(q_X509V3_EXT_d2i(ext));
-
- QVariantMap result;
- result[QLatin1String("ca")] = basic->ca ? true : false;
- if (basic->pathlen)
- result[QLatin1String("pathLenConstraint")] = (qlonglong)q_ASN1_INTEGER_get(basic->pathlen);
-
- q_BASIC_CONSTRAINTS_free(basic);
- return result;
- }
- break;
- case NID_info_access:
- {
- AUTHORITY_INFO_ACCESS *info = reinterpret_cast<AUTHORITY_INFO_ACCESS *>(q_X509V3_EXT_d2i(ext));
-
- QVariantMap result;
- for (int i=0; i < q_SKM_sk_num(ACCESS_DESCRIPTION, info); i++) {
- ACCESS_DESCRIPTION *ad = q_SKM_sk_value(ACCESS_DESCRIPTION, info, i);
-
- GENERAL_NAME *name = ad->location;
- if (name->type == GEN_URI) {
- int len = q_ASN1_STRING_length(name->d.uniformResourceIdentifier);
- if (len < 0 || len >= 8192) {
- // broken name
- continue;
- }
-
- const char *uriStr = reinterpret_cast<const char *>(q_ASN1_STRING_data(name->d.uniformResourceIdentifier));
- const QString uri = QString::fromUtf8(uriStr, len);
-
- result[QString::fromUtf8(QSslCertificatePrivate::asn1ObjectName(ad->method))] = uri;
- } else {
- qWarning() << "Strange location type" << name->type;
- }
- }
-
-#if OPENSSL_VERSION_NUMBER >= 0x10000000L
- q_sk_pop_free((_STACK*)info, reinterpret_cast<void(*)(void*)>(q_sk_free));
-#else
- q_sk_pop_free((STACK*)info, reinterpret_cast<void(*)(void*)>(q_sk_free));
-#endif
- return result;
- }
- break;
- case NID_subject_key_identifier:
- {
- void *ext_internal = q_X509V3_EXT_d2i(ext);
-
- // we cast away the const-ness here because some versions of openssl
- // don't use const for the parameters in the functions pointers stored
- // in the object.
- X509V3_EXT_METHOD *meth = const_cast<X509V3_EXT_METHOD *>(q_X509V3_EXT_get(ext));
-
- return QVariant(QString::fromUtf8(meth->i2s(meth, ext_internal)));
- }
- break;
- case NID_authority_key_identifier:
- {
- AUTHORITY_KEYID *auth_key = reinterpret_cast<AUTHORITY_KEYID *>(q_X509V3_EXT_d2i(ext));
-
- QVariantMap result;
-
- // keyid
- if (auth_key->keyid) {
- QByteArray keyid(reinterpret_cast<const char *>(auth_key->keyid->data),
- auth_key->keyid->length);
- result[QLatin1String("keyid")] = keyid.toHex();
- }
-
- // issuer
- // TODO: GENERAL_NAMES
-
- // serial
- if (auth_key->serial)
- result[QLatin1String("serial")] = (qlonglong)q_ASN1_INTEGER_get(auth_key->serial);
-
- q_AUTHORITY_KEYID_free(auth_key);
- return result;
- }
- break;
- }
-
- return QVariant();
-}
-
-QSslCertificateExtension QSslCertificatePrivate::convertExtension(X509_EXTENSION *ext)
-{
- QSslCertificateExtension result;
-
- ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext);
- QByteArray oid = QSslCertificatePrivate::asn1ObjectId(obj);
- QByteArray name = QSslCertificatePrivate::asn1ObjectName(obj);
-
- result.d->oid = QString::fromUtf8(oid);
- result.d->name = QString::fromUtf8(name);
-
- bool critical = q_X509_EXTENSION_get_critical(ext);
- result.d->critical = critical;
-
- // Lets see if we have custom support for this one
- QVariant extensionValue = x509ExtensionToValue(ext);
- if (extensionValue.isValid()) {
- result.d->value = extensionValue;
- result.d->supported = true;
-
- return result;
- }
-
- extensionValue = x509UnknownExtensionToValue(ext);
- if (extensionValue.isValid()) {
- result.d->value = extensionValue;
- result.d->supported = false;
- return result;
- }
-
- return result;
-}
/*!
+ \fn QList<QSslCertificateExtension> QSslCertificate::extensions() const
+
Returns a list containing the X509 extensions of this certificate.
\since 5.0
*/
-QList<QSslCertificateExtension> QSslCertificate::extensions() const
-{
- QList<QSslCertificateExtension> result;
-
- if (!d->x509)
- return result;
-
- int count = q_X509_get_ext_count(d->x509);
-
- for (int i=0; i < count; i++) {
- X509_EXTENSION *ext = q_X509_get_ext(d->x509, i);
- result << QSslCertificatePrivate::convertExtension(ext);
- }
-
- return result;
-}
/*!
+ \fn QByteArray QSslCertificate::toPem() const
+
Returns this certificate converted to a PEM (Base64) encoded
representation.
*/
-QByteArray QSslCertificate::toPem() const
-{
- if (!d->x509)
- return QByteArray();
- return d->QByteArray_from_X509(d->x509, QSsl::Pem);
-}
/*!
+ \fn QByteArray QSslCertificate::toDer() const
+
Returns this certificate converted to a DER (binary) encoded
representation.
*/
-QByteArray QSslCertificate::toDer() const
-{
- if (!d->x509)
- return QByteArray();
- return d->QByteArray_from_X509(d->x509, QSsl::Der);
-}
/*!
+ \fn QString QSslCertificate::toText() const
+
Returns this certificate converted to a human-readable text
representation.
\since 5.0
*/
-QString QSslCertificate::toText() const
-{
- if (!d->x509)
- return QString();
- return d->text_from_X509(d->x509);
-}
/*!
Searches all files in the \a path for certificates encoded in the
@@ -963,216 +571,24 @@ QList<QSslError> QSslCertificate::verify(QList<QSslCertificate> certificateChain
return QSslSocketBackendPrivate::verify(certificateChain, hostName);
}
-void QSslCertificatePrivate::init(const QByteArray &data, QSsl::EncodingFormat format)
-{
- if (!data.isEmpty()) {
- QList<QSslCertificate> certs = (format == QSsl::Pem)
- ? certificatesFromPem(data, 1)
- : certificatesFromDer(data, 1);
- if (!certs.isEmpty()) {
- *this = *certs.first().d;
- if (x509)
- x509 = q_X509_dup(x509);
- }
- }
-}
-
-#define BEGINCERTSTRING "-----BEGIN CERTIFICATE-----"
-#define ENDCERTSTRING "-----END CERTIFICATE-----"
-
-// ### refactor against QSsl::pemFromDer() etc. (to avoid redundant implementations)
-QByteArray QSslCertificatePrivate::QByteArray_from_X509(X509 *x509, QSsl::EncodingFormat format)
-{
- if (!x509) {
- qWarning("QSslSocketBackendPrivate::X509_to_QByteArray: null X509");
- return QByteArray();
- }
-
- // Use i2d_X509 to convert the X509 to an array.
- int length = q_i2d_X509(x509, 0);
- QByteArray array;
- array.resize(length);
- char *data = array.data();
- char **dataP = &data;
- unsigned char **dataPu = (unsigned char **)dataP;
- if (q_i2d_X509(x509, dataPu) < 0)
- return QByteArray();
-
- if (format == QSsl::Der)
- return array;
-
- // Convert to Base64 - wrap at 64 characters.
- array = array.toBase64();
- QByteArray tmp;
- for (int i = 0; i <= array.size() - 64; i += 64) {
- tmp += QByteArray::fromRawData(array.data() + i, 64);
- tmp += '\n';
- }
- if (int remainder = array.size() % 64) {
- tmp += QByteArray::fromRawData(array.data() + array.size() - remainder, remainder);
- tmp += '\n';
- }
-
- return BEGINCERTSTRING "\n" + tmp + ENDCERTSTRING "\n";
-}
-
-QString QSslCertificatePrivate::text_from_X509(X509 *x509)
-{
- if (!x509) {
- qWarning("QSslSocketBackendPrivate::text_from_X509: null X509");
- return QString();
- }
-
- QByteArray result;
- BIO *bio = q_BIO_new(q_BIO_s_mem());
- if (!bio)
- return QString();
-
- q_X509_print(bio, x509);
-
- QVarLengthArray<char, 16384> data;
- int count = q_BIO_read(bio, data.data(), 16384);
- if ( count > 0 ) {
- result = QByteArray( data.data(), count );
- }
-
- q_BIO_free(bio);
-
- return QString::fromLatin1(result);
-}
-
-QByteArray QSslCertificatePrivate::asn1ObjectId(ASN1_OBJECT *object)
-{
- char buf[80]; // The openssl docs a buffer length of 80 should be more than enough
- q_OBJ_obj2txt(buf, sizeof(buf), object, 1); // the 1 says always use the oid not the long name
-
- return QByteArray(buf);
-}
-
-
-QByteArray QSslCertificatePrivate::asn1ObjectName(ASN1_OBJECT *object)
-{
- int nid = q_OBJ_obj2nid(object);
- if (nid != NID_undef)
- return QByteArray(q_OBJ_nid2sn(nid));
-
- return asn1ObjectId(object);
-}
-
-static QMap<QByteArray, QString> _q_mapFromX509Name(X509_NAME *name)
-{
- QMap<QByteArray, QString> info;
- for (int i = 0; i < q_X509_NAME_entry_count(name); ++i) {
- X509_NAME_ENTRY *e = q_X509_NAME_get_entry(name, i);
-
- QByteArray name = QSslCertificatePrivate::asn1ObjectName(q_X509_NAME_ENTRY_get_object(e));
- unsigned char *data = 0;
- int size = q_ASN1_STRING_to_UTF8(&data, q_X509_NAME_ENTRY_get_data(e));
- info.insertMulti(name, QString::fromUtf8((char*)data, size));
- q_CRYPTO_free(data);
- }
-
- return info;
-}
-
-QSslCertificate QSslCertificatePrivate::QSslCertificate_from_X509(X509 *x509)
-{
- QSslCertificate certificate;
- if (!x509 || !QSslSocket::supportsSsl())
- return certificate;
-
- ASN1_TIME *nbef = q_X509_get_notBefore(x509);
- ASN1_TIME *naft = q_X509_get_notAfter(x509);
- certificate.d->notValidBefore = q_getTimeFromASN1(nbef);
- certificate.d->notValidAfter = q_getTimeFromASN1(naft);
- certificate.d->null = false;
- certificate.d->x509 = q_X509_dup(x509);
-
- return certificate;
-}
-
-static bool matchLineFeed(const QByteArray &pem, int *offset)
-{
- char ch = 0;
-
- // ignore extra whitespace at the end of the line
- while (*offset < pem.size() && (ch = pem.at(*offset)) == ' ')
- ++*offset;
-
- if (ch == '\n') {
- *offset += 1;
- return true;
- }
- if (ch == '\r' && pem.size() > (*offset + 1) && pem.at(*offset + 1) == '\n') {
- *offset += 2;
- return true;
- }
- return false;
-}
-
-QList<QSslCertificate> QSslCertificatePrivate::certificatesFromPem(const QByteArray &pem, int count)
-{
- QList<QSslCertificate> certificates;
- QSslSocketPrivate::ensureInitialized();
-
- int offset = 0;
- while (count == -1 || certificates.size() < count) {
- int startPos = pem.indexOf(BEGINCERTSTRING, offset);
- if (startPos == -1)
- break;
- startPos += sizeof(BEGINCERTSTRING) - 1;
- if (!matchLineFeed(pem, &startPos))
- break;
-
- int endPos = pem.indexOf(ENDCERTSTRING, startPos);
- if (endPos == -1)
- break;
-
- offset = endPos + sizeof(ENDCERTSTRING) - 1;
- if (offset < pem.size() && !matchLineFeed(pem, &offset))
- break;
-
- QByteArray decoded = QByteArray::fromBase64(
- QByteArray::fromRawData(pem.data() + startPos, endPos - startPos));
-#if OPENSSL_VERSION_NUMBER >= 0x00908000L
- const unsigned char *data = (const unsigned char *)decoded.data();
-#else
- unsigned char *data = (unsigned char *)decoded.data();
-#endif
-
- if (X509 *x509 = q_d2i_X509(0, &data, decoded.size())) {
- certificates << QSslCertificate_from_X509(x509);
- q_X509_free(x509);
- }
- }
+/*!
+ \since 5.4
- return certificates;
-}
+ Imports a PKCS#12 (pfx) file from the specified \a device. A PKCS#12
+ file is a bundle that can contain a number of certificates and keys.
+ This method reads a single \a key, its \a certificate and any
+ associated \a caCertificates from the bundle. If a \a passPhrase is
+ specified then this will be used to decrypt the bundle. Returns
+ \c true if the PKCS#12 file was successfully loaded.
-QList<QSslCertificate> QSslCertificatePrivate::certificatesFromDer(const QByteArray &der, int count)
+ \note The \a device must be open and ready to be read from.
+ */
+bool QSslCertificate::importPKCS12(QIODevice *device,
+ QSslKey *key, QSslCertificate *certificate,
+ QList<QSslCertificate> *caCertificates,
+ const QByteArray &passPhrase)
{
- QList<QSslCertificate> certificates;
- QSslSocketPrivate::ensureInitialized();
-
-
-#if OPENSSL_VERSION_NUMBER >= 0x00908000L
- const unsigned char *data = (const unsigned char *)der.data();
-#else
- unsigned char *data = (unsigned char *)der.data();
-#endif
- int size = der.size();
-
- while (count == -1 || certificates.size() < count) {
- if (X509 *x509 = q_d2i_X509(0, &data, size)) {
- certificates << QSslCertificate_from_X509(x509);
- q_X509_free(x509);
- } else {
- break;
- }
- size -= ((char *)data - der.data());
- }
-
- return certificates;
+ return QSslSocketBackendPrivate::importPKCS12(device, key, certificate, caCertificates, passPhrase);
}
// These certificates are known to be fraudulent and were created during the comodo
@@ -1237,6 +653,25 @@ bool QSslCertificatePrivate::isBlacklisted(const QSslCertificate &certificate)
return false;
}
+QByteArray QSslCertificatePrivate::subjectInfoToString(QSslCertificate::SubjectInfo info)
+{
+ QByteArray str;
+ switch (info) {
+ case QSslCertificate::Organization: str = QByteArray("O"); break;
+ case QSslCertificate::CommonName: str = QByteArray("CN"); break;
+ case QSslCertificate::LocalityName: str = QByteArray("L"); break;
+ case QSslCertificate::OrganizationalUnitName: str = QByteArray("OU"); break;
+ case QSslCertificate::CountryName: str = QByteArray("C"); break;
+ case QSslCertificate::StateOrProvinceName: str = QByteArray("ST"); break;
+ case QSslCertificate::DistinguishedNameQualifier: str = QByteArray("dnQualifier"); break;
+ case QSslCertificate::SerialNumber: str = QByteArray("serialNumber"); break;
+ case QSslCertificate::EmailAddress: str = QByteArray("emailAddress"); break;
+ }
+ return str;
+}
+
+
+
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const QSslCertificate &certificate)
{
diff --git a/src/network/ssl/qsslcertificate.h b/src/network/ssl/qsslcertificate.h
index 988071eb9d..2217eb7fb9 100644
--- a/src/network/ssl/qsslcertificate.h
+++ b/src/network/ssl/qsslcertificate.h
@@ -105,6 +105,7 @@ public:
}
#endif
bool isBlacklisted() const;
+ bool isSelfSigned() const;
void clear();
// Certificate info
@@ -141,6 +142,11 @@ public:
static QList<QSslError> verify(QList<QSslCertificate> certificateChain, const QString &hostName = QString());
+ static bool importPKCS12(QIODevice *device,
+ QSslKey *key, QSslCertificate *cert,
+ QList<QSslCertificate> *caCertificates=0,
+ const QByteArray &passPhrase=QByteArray());
+
Qt::HANDLE handle() const;
private:
diff --git a/src/network/ssl/qsslcertificate_openssl.cpp b/src/network/ssl/qsslcertificate_openssl.cpp
new file mode 100644
index 0000000000..664f5eba08
--- /dev/null
+++ b/src/network/ssl/qsslcertificate_openssl.cpp
@@ -0,0 +1,699 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsslsocket_openssl_symbols_p.h"
+#include "qsslcertificate_p.h"
+#include "qsslkey_p.h"
+#include "qsslcertificateextension_p.h"
+
+#include <QtCore/private/qmutexpool_p.h>
+
+QT_BEGIN_NAMESPACE
+
+// forward declaration
+static QMap<QByteArray, QString> _q_mapFromX509Name(X509_NAME *name);
+
+bool QSslCertificate::operator==(const QSslCertificate &other) const
+{
+ if (d == other.d)
+ return true;
+ if (d->null && other.d->null)
+ return true;
+ if (d->x509 && other.d->x509)
+ return q_X509_cmp(d->x509, other.d->x509) == 0;
+ return false;
+}
+
+bool QSslCertificate::isNull() const
+{
+ return d->null;
+}
+
+bool QSslCertificate::isSelfSigned() const
+{
+ if (!d->x509)
+ return false;
+
+ return (q_X509_check_issued(d->x509, d->x509) == X509_V_OK);
+}
+
+QByteArray QSslCertificate::version() const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ if (d->versionString.isEmpty() && d->x509)
+ d->versionString =
+ QByteArray::number(qlonglong(q_ASN1_INTEGER_get(d->x509->cert_info->version)) + 1);
+
+ return d->versionString;
+}
+
+QByteArray QSslCertificate::serialNumber() const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ if (d->serialNumberString.isEmpty() && d->x509) {
+ ASN1_INTEGER *serialNumber = d->x509->cert_info->serialNumber;
+ QByteArray hexString;
+ hexString.reserve(serialNumber->length * 3);
+ for (int a = 0; a < serialNumber->length; ++a) {
+ hexString += QByteArray::number(serialNumber->data[a], 16).rightJustified(2, '0');
+ hexString += ':';
+ }
+ hexString.chop(1);
+ d->serialNumberString = hexString;
+ }
+ return d->serialNumberString;
+}
+
+QStringList QSslCertificate::issuerInfo(SubjectInfo info) const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ // lazy init
+ if (d->issuerInfo.isEmpty() && d->x509)
+ d->issuerInfo =
+ _q_mapFromX509Name(q_X509_get_issuer_name(d->x509));
+
+ return d->issuerInfo.values(d->subjectInfoToString(info));
+}
+
+QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ // lazy init
+ if (d->issuerInfo.isEmpty() && d->x509)
+ d->issuerInfo =
+ _q_mapFromX509Name(q_X509_get_issuer_name(d->x509));
+
+ return d->issuerInfo.values(attribute);
+}
+
+QStringList QSslCertificate::subjectInfo(SubjectInfo info) const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ // lazy init
+ if (d->subjectInfo.isEmpty() && d->x509)
+ d->subjectInfo =
+ _q_mapFromX509Name(q_X509_get_subject_name(d->x509));
+
+ return d->subjectInfo.values(d->subjectInfoToString(info));
+}
+
+QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ // lazy init
+ if (d->subjectInfo.isEmpty() && d->x509)
+ d->subjectInfo =
+ _q_mapFromX509Name(q_X509_get_subject_name(d->x509));
+
+ return d->subjectInfo.values(attribute);
+}
+
+QList<QByteArray> QSslCertificate::subjectInfoAttributes() const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ // lazy init
+ if (d->subjectInfo.isEmpty() && d->x509)
+ d->subjectInfo =
+ _q_mapFromX509Name(q_X509_get_subject_name(d->x509));
+
+ return d->subjectInfo.uniqueKeys();
+}
+
+QList<QByteArray> QSslCertificate::issuerInfoAttributes() const
+{
+ QMutexLocker lock(QMutexPool::globalInstanceGet(d.data()));
+ // lazy init
+ if (d->issuerInfo.isEmpty() && d->x509)
+ d->issuerInfo =
+ _q_mapFromX509Name(q_X509_get_issuer_name(d->x509));
+
+ return d->issuerInfo.uniqueKeys();
+}
+
+QMultiMap<QSsl::AlternativeNameEntryType, QString> QSslCertificate::subjectAlternativeNames() const
+{
+ QMultiMap<QSsl::AlternativeNameEntryType, QString> result;
+
+ if (!d->x509)
+ return result;
+
+ STACK_OF(GENERAL_NAME) *altNames = (STACK_OF(GENERAL_NAME)*)q_X509_get_ext_d2i(d->x509, NID_subject_alt_name, 0, 0);
+
+ if (altNames) {
+ for (int i = 0; i < q_sk_GENERAL_NAME_num(altNames); ++i) {
+ const GENERAL_NAME *genName = q_sk_GENERAL_NAME_value(altNames, i);
+ if (genName->type != GEN_DNS && genName->type != GEN_EMAIL)
+ continue;
+
+ int len = q_ASN1_STRING_length(genName->d.ia5);
+ if (len < 0 || len >= 8192) {
+ // broken name
+ continue;
+ }
+
+ const char *altNameStr = reinterpret_cast<const char *>(q_ASN1_STRING_data(genName->d.ia5));
+ const QString altName = QString::fromLatin1(altNameStr, len);
+ if (genName->type == GEN_DNS)
+ result.insert(QSsl::DnsEntry, altName);
+ else if (genName->type == GEN_EMAIL)
+ result.insert(QSsl::EmailEntry, altName);
+ }
+ q_sk_pop_free((STACK*)altNames, reinterpret_cast<void(*)(void*)>(q_sk_free));
+ }
+
+ return result;
+}
+
+QDateTime QSslCertificate::effectiveDate() const
+{
+ return d->notValidBefore;
+}
+
+QDateTime QSslCertificate::expiryDate() const
+{
+ return d->notValidAfter;
+}
+
+Qt::HANDLE QSslCertificate::handle() const
+{
+ return Qt::HANDLE(d->x509);
+}
+
+QSslKey QSslCertificate::publicKey() const
+{
+ if (!d->x509)
+ return QSslKey();
+
+ QSslKey key;
+
+ key.d->type = QSsl::PublicKey;
+ X509_PUBKEY *xkey = d->x509->cert_info->key;
+ EVP_PKEY *pkey = q_X509_PUBKEY_get(xkey);
+ Q_ASSERT(pkey);
+
+ if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA) {
+ key.d->rsa = q_EVP_PKEY_get1_RSA(pkey);
+ key.d->algorithm = QSsl::Rsa;
+ key.d->isNull = false;
+ } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DSA) {
+ key.d->dsa = q_EVP_PKEY_get1_DSA(pkey);
+ key.d->algorithm = QSsl::Dsa;
+ key.d->isNull = false;
+ } else if (q_EVP_PKEY_type(pkey->type) == EVP_PKEY_DH) {
+ // DH unsupported
+ } else {
+ // error?
+ }
+
+ q_EVP_PKEY_free(pkey);
+ return key;
+}
+
+/*
+ * Convert unknown extensions to a QVariant.
+ */
+static QVariant x509UnknownExtensionToValue(X509_EXTENSION *ext)
+{
+ // Get the extension specific method object if available
+ // we cast away the const-ness here because some versions of openssl
+ // don't use const for the parameters in the functions pointers stored
+ // in the object.
+ X509V3_EXT_METHOD *meth = const_cast<X509V3_EXT_METHOD *>(q_X509V3_EXT_get(ext));
+ if (!meth) {
+ ASN1_OCTET_STRING *value = q_X509_EXTENSION_get_data(ext);
+ QByteArray result( reinterpret_cast<const char *>(q_ASN1_STRING_data(value)),
+ q_ASN1_STRING_length(value));
+ return result;
+ }
+
+ //const unsigned char *data = ext->value->data;
+ void *ext_internal = q_X509V3_EXT_d2i(ext);
+
+ // If this extension can be converted
+ if (meth->i2v && ext_internal) {
+ STACK_OF(CONF_VALUE) *val = meth->i2v(meth, ext_internal, 0);
+
+ QVariantMap map;
+ QVariantList list;
+ bool isMap = false;
+
+ for (int j = 0; j < q_SKM_sk_num(CONF_VALUE, val); j++) {
+ CONF_VALUE *nval = q_SKM_sk_value(CONF_VALUE, val, j);
+ if (nval->name && nval->value) {
+ isMap = true;
+ map[QString::fromUtf8(nval->name)] = QString::fromUtf8(nval->value);
+ } else if (nval->name) {
+ list << QString::fromUtf8(nval->name);
+ } else if (nval->value) {
+ list << QString::fromUtf8(nval->value);
+ }
+ }
+
+ if (isMap)
+ return map;
+ else
+ return list;
+ } else if (meth->i2s && ext_internal) {
+ //qDebug() << meth->i2s(meth, ext_internal);
+ QVariant result(QString::fromUtf8(meth->i2s(meth, ext_internal)));
+ return result;
+ } else if (meth->i2r && ext_internal) {
+ QByteArray result;
+
+ BIO *bio = q_BIO_new(q_BIO_s_mem());
+ if (!bio)
+ return result;
+
+ meth->i2r(meth, ext_internal, bio, 0);
+
+ char *bio_buffer;
+ long bio_size = q_BIO_get_mem_data(bio, &bio_buffer);
+ result = QByteArray(bio_buffer, bio_size);
+
+ q_BIO_free(bio);
+ return result;
+ }
+
+ return QVariant();
+}
+
+/*
+ * Convert extensions to a variant. The naming of the keys of the map are
+ * taken from RFC 5280, however we decided the capitalisation in the RFC
+ * was too silly for the real world.
+ */
+static QVariant x509ExtensionToValue(X509_EXTENSION *ext)
+{
+ ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext);
+ int nid = q_OBJ_obj2nid(obj);
+
+ switch (nid) {
+ case NID_basic_constraints:
+ {
+ BASIC_CONSTRAINTS *basic = reinterpret_cast<BASIC_CONSTRAINTS *>(q_X509V3_EXT_d2i(ext));
+
+ QVariantMap result;
+ result[QLatin1String("ca")] = basic->ca ? true : false;
+ if (basic->pathlen)
+ result[QLatin1String("pathLenConstraint")] = (qlonglong)q_ASN1_INTEGER_get(basic->pathlen);
+
+ q_BASIC_CONSTRAINTS_free(basic);
+ return result;
+ }
+ break;
+ case NID_info_access:
+ {
+ AUTHORITY_INFO_ACCESS *info = reinterpret_cast<AUTHORITY_INFO_ACCESS *>(q_X509V3_EXT_d2i(ext));
+
+ QVariantMap result;
+ for (int i=0; i < q_SKM_sk_num(ACCESS_DESCRIPTION, info); i++) {
+ ACCESS_DESCRIPTION *ad = q_SKM_sk_value(ACCESS_DESCRIPTION, info, i);
+
+ GENERAL_NAME *name = ad->location;
+ if (name->type == GEN_URI) {
+ int len = q_ASN1_STRING_length(name->d.uniformResourceIdentifier);
+ if (len < 0 || len >= 8192) {
+ // broken name
+ continue;
+ }
+
+ const char *uriStr = reinterpret_cast<const char *>(q_ASN1_STRING_data(name->d.uniformResourceIdentifier));
+ const QString uri = QString::fromUtf8(uriStr, len);
+
+ result[QString::fromUtf8(QSslCertificatePrivate::asn1ObjectName(ad->method))] = uri;
+ } else {
+ qWarning() << "Strange location type" << name->type;
+ }
+ }
+
+#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+ q_sk_pop_free((_STACK*)info, reinterpret_cast<void(*)(void*)>(q_sk_free));
+#else
+ q_sk_pop_free((STACK*)info, reinterpret_cast<void(*)(void*)>(q_sk_free));
+#endif
+ return result;
+ }
+ break;
+ case NID_subject_key_identifier:
+ {
+ void *ext_internal = q_X509V3_EXT_d2i(ext);
+
+ // we cast away the const-ness here because some versions of openssl
+ // don't use const for the parameters in the functions pointers stored
+ // in the object.
+ X509V3_EXT_METHOD *meth = const_cast<X509V3_EXT_METHOD *>(q_X509V3_EXT_get(ext));
+
+ return QVariant(QString::fromUtf8(meth->i2s(meth, ext_internal)));
+ }
+ break;
+ case NID_authority_key_identifier:
+ {
+ AUTHORITY_KEYID *auth_key = reinterpret_cast<AUTHORITY_KEYID *>(q_X509V3_EXT_d2i(ext));
+
+ QVariantMap result;
+
+ // keyid
+ if (auth_key->keyid) {
+ QByteArray keyid(reinterpret_cast<const char *>(auth_key->keyid->data),
+ auth_key->keyid->length);
+ result[QLatin1String("keyid")] = keyid.toHex();
+ }
+
+ // issuer
+ // TODO: GENERAL_NAMES
+
+ // serial
+ if (auth_key->serial)
+ result[QLatin1String("serial")] = (qlonglong)q_ASN1_INTEGER_get(auth_key->serial);
+
+ q_AUTHORITY_KEYID_free(auth_key);
+ return result;
+ }
+ break;
+ }
+
+ return QVariant();
+}
+
+QSslCertificateExtension QSslCertificatePrivate::convertExtension(X509_EXTENSION *ext)
+{
+ QSslCertificateExtension result;
+
+ ASN1_OBJECT *obj = q_X509_EXTENSION_get_object(ext);
+ QByteArray oid = QSslCertificatePrivate::asn1ObjectId(obj);
+ QByteArray name = QSslCertificatePrivate::asn1ObjectName(obj);
+
+ result.d->oid = QString::fromUtf8(oid);
+ result.d->name = QString::fromUtf8(name);
+
+ bool critical = q_X509_EXTENSION_get_critical(ext);
+ result.d->critical = critical;
+
+ // Lets see if we have custom support for this one
+ QVariant extensionValue = x509ExtensionToValue(ext);
+ if (extensionValue.isValid()) {
+ result.d->value = extensionValue;
+ result.d->supported = true;
+
+ return result;
+ }
+
+ extensionValue = x509UnknownExtensionToValue(ext);
+ if (extensionValue.isValid()) {
+ result.d->value = extensionValue;
+ result.d->supported = false;
+ return result;
+ }
+
+ return result;
+}
+
+QList<QSslCertificateExtension> QSslCertificate::extensions() const
+{
+ QList<QSslCertificateExtension> result;
+
+ if (!d->x509)
+ return result;
+
+ int count = q_X509_get_ext_count(d->x509);
+
+ for (int i=0; i < count; i++) {
+ X509_EXTENSION *ext = q_X509_get_ext(d->x509, i);
+ result << QSslCertificatePrivate::convertExtension(ext);
+ }
+
+ return result;
+}
+
+QByteArray QSslCertificate::toPem() const
+{
+ if (!d->x509)
+ return QByteArray();
+ return d->QByteArray_from_X509(d->x509, QSsl::Pem);
+}
+
+QByteArray QSslCertificate::toDer() const
+{
+ if (!d->x509)
+ return QByteArray();
+ return d->QByteArray_from_X509(d->x509, QSsl::Der);
+}
+
+QString QSslCertificate::toText() const
+{
+ if (!d->x509)
+ return QString();
+ return d->text_from_X509(d->x509);
+}
+
+#define BEGINCERTSTRING "-----BEGIN CERTIFICATE-----"
+#define ENDCERTSTRING "-----END CERTIFICATE-----"
+
+void QSslCertificatePrivate::init(const QByteArray &data, QSsl::EncodingFormat format)
+{
+ if (!data.isEmpty()) {
+ QList<QSslCertificate> certs = (format == QSsl::Pem)
+ ? certificatesFromPem(data, 1)
+ : certificatesFromDer(data, 1);
+ if (!certs.isEmpty()) {
+ *this = *certs.first().d;
+ if (x509)
+ x509 = q_X509_dup(x509);
+ }
+ }
+}
+
+// ### refactor against QSsl::pemFromDer() etc. (to avoid redundant implementations)
+QByteArray QSslCertificatePrivate::QByteArray_from_X509(X509 *x509, QSsl::EncodingFormat format)
+{
+ if (!x509) {
+ qWarning("QSslSocketBackendPrivate::X509_to_QByteArray: null X509");
+ return QByteArray();
+ }
+
+ // Use i2d_X509 to convert the X509 to an array.
+ int length = q_i2d_X509(x509, 0);
+ QByteArray array;
+ array.resize(length);
+ char *data = array.data();
+ char **dataP = &data;
+ unsigned char **dataPu = (unsigned char **)dataP;
+ if (q_i2d_X509(x509, dataPu) < 0)
+ return QByteArray();
+
+ if (format == QSsl::Der)
+ return array;
+
+ // Convert to Base64 - wrap at 64 characters.
+ array = array.toBase64();
+ QByteArray tmp;
+ for (int i = 0; i <= array.size() - 64; i += 64) {
+ tmp += QByteArray::fromRawData(array.data() + i, 64);
+ tmp += '\n';
+ }
+ if (int remainder = array.size() % 64) {
+ tmp += QByteArray::fromRawData(array.data() + array.size() - remainder, remainder);
+ tmp += '\n';
+ }
+
+ return BEGINCERTSTRING "\n" + tmp + ENDCERTSTRING "\n";
+}
+
+QString QSslCertificatePrivate::text_from_X509(X509 *x509)
+{
+ if (!x509) {
+ qWarning("QSslSocketBackendPrivate::text_from_X509: null X509");
+ return QString();
+ }
+
+ QByteArray result;
+ BIO *bio = q_BIO_new(q_BIO_s_mem());
+ if (!bio)
+ return QString();
+
+ q_X509_print(bio, x509);
+
+ QVarLengthArray<char, 16384> data;
+ int count = q_BIO_read(bio, data.data(), 16384);
+ if ( count > 0 ) {
+ result = QByteArray( data.data(), count );
+ }
+
+ q_BIO_free(bio);
+
+ return QString::fromLatin1(result);
+}
+
+QByteArray QSslCertificatePrivate::asn1ObjectId(ASN1_OBJECT *object)
+{
+ char buf[80]; // The openssl docs a buffer length of 80 should be more than enough
+ q_OBJ_obj2txt(buf, sizeof(buf), object, 1); // the 1 says always use the oid not the long name
+
+ return QByteArray(buf);
+}
+
+
+QByteArray QSslCertificatePrivate::asn1ObjectName(ASN1_OBJECT *object)
+{
+ int nid = q_OBJ_obj2nid(object);
+ if (nid != NID_undef)
+ return QByteArray(q_OBJ_nid2sn(nid));
+
+ return asn1ObjectId(object);
+}
+
+static QMap<QByteArray, QString> _q_mapFromX509Name(X509_NAME *name)
+{
+ QMap<QByteArray, QString> info;
+ for (int i = 0; i < q_X509_NAME_entry_count(name); ++i) {
+ X509_NAME_ENTRY *e = q_X509_NAME_get_entry(name, i);
+
+ QByteArray name = QSslCertificatePrivate::asn1ObjectName(q_X509_NAME_ENTRY_get_object(e));
+ unsigned char *data = 0;
+ int size = q_ASN1_STRING_to_UTF8(&data, q_X509_NAME_ENTRY_get_data(e));
+ info.insertMulti(name, QString::fromUtf8((char*)data, size));
+ q_CRYPTO_free(data);
+ }
+
+ return info;
+}
+
+QSslCertificate QSslCertificatePrivate::QSslCertificate_from_X509(X509 *x509)
+{
+ QSslCertificate certificate;
+ if (!x509 || !QSslSocket::supportsSsl())
+ return certificate;
+
+ ASN1_TIME *nbef = q_X509_get_notBefore(x509);
+ ASN1_TIME *naft = q_X509_get_notAfter(x509);
+ certificate.d->notValidBefore = q_getTimeFromASN1(nbef);
+ certificate.d->notValidAfter = q_getTimeFromASN1(naft);
+ certificate.d->null = false;
+ certificate.d->x509 = q_X509_dup(x509);
+
+ return certificate;
+}
+
+static bool matchLineFeed(const QByteArray &pem, int *offset)
+{
+ char ch = 0;
+
+ // ignore extra whitespace at the end of the line
+ while (*offset < pem.size() && (ch = pem.at(*offset)) == ' ')
+ ++*offset;
+
+ if (ch == '\n') {
+ *offset += 1;
+ return true;
+ }
+ if (ch == '\r' && pem.size() > (*offset + 1) && pem.at(*offset + 1) == '\n') {
+ *offset += 2;
+ return true;
+ }
+ return false;
+}
+
+QList<QSslCertificate> QSslCertificatePrivate::certificatesFromPem(const QByteArray &pem, int count)
+{
+ QList<QSslCertificate> certificates;
+ QSslSocketPrivate::ensureInitialized();
+
+ int offset = 0;
+ while (count == -1 || certificates.size() < count) {
+ int startPos = pem.indexOf(BEGINCERTSTRING, offset);
+ if (startPos == -1)
+ break;
+ startPos += sizeof(BEGINCERTSTRING) - 1;
+ if (!matchLineFeed(pem, &startPos))
+ break;
+
+ int endPos = pem.indexOf(ENDCERTSTRING, startPos);
+ if (endPos == -1)
+ break;
+
+ offset = endPos + sizeof(ENDCERTSTRING) - 1;
+ if (offset < pem.size() && !matchLineFeed(pem, &offset))
+ break;
+
+ QByteArray decoded = QByteArray::fromBase64(
+ QByteArray::fromRawData(pem.data() + startPos, endPos - startPos));
+#if OPENSSL_VERSION_NUMBER >= 0x00908000L
+ const unsigned char *data = (const unsigned char *)decoded.data();
+#else
+ unsigned char *data = (unsigned char *)decoded.data();
+#endif
+
+ if (X509 *x509 = q_d2i_X509(0, &data, decoded.size())) {
+ certificates << QSslCertificate_from_X509(x509);
+ q_X509_free(x509);
+ }
+ }
+
+ return certificates;
+}
+
+QList<QSslCertificate> QSslCertificatePrivate::certificatesFromDer(const QByteArray &der, int count)
+{
+ QList<QSslCertificate> certificates;
+ QSslSocketPrivate::ensureInitialized();
+
+
+#if OPENSSL_VERSION_NUMBER >= 0x00908000L
+ const unsigned char *data = (const unsigned char *)der.data();
+#else
+ unsigned char *data = (unsigned char *)der.data();
+#endif
+ int size = der.size();
+
+ while (count == -1 || certificates.size() < count) {
+ if (X509 *x509 = q_d2i_X509(0, &data, size)) {
+ certificates << QSslCertificate_from_X509(x509);
+ q_X509_free(x509);
+ } else {
+ break;
+ }
+ size -= ((char *)data - der.data());
+ }
+
+ return certificates;
+}
+
+QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslcertificate_p.h b/src/network/ssl/qsslcertificate_p.h
index 6cf6974543..b0c99e545d 100644
--- a/src/network/ssl/qsslcertificate_p.h
+++ b/src/network/ssl/qsslcertificate_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -40,8 +40,8 @@
****************************************************************************/
-#ifndef QSSLCERTIFICATE_P_H
-#define QSSLCERTIFICATE_P_H
+#ifndef QSSLCERTIFICATE_OPENSSL_P_H
+#define QSSLCERTIFICATE_OPENSSL_P_H
#include "qsslcertificate.h"
@@ -61,10 +61,23 @@
#include <QtCore/qdatetime.h>
#include <QtCore/qmap.h>
+#ifndef QT_NO_OPENSSL
#include <openssl/x509.h>
+#else
+struct X509;
+struct X509_EXTENSION;
+struct ASN1_OBJECT;
+#endif
+
+#ifdef Q_OS_WINRT
+#include <wrl.h>
+#include <windows.security.cryptography.certificates.h>
+#endif
QT_BEGIN_NAMESPACE
+// forward declaration
+
class QSslCertificatePrivate
{
public:
@@ -76,8 +89,10 @@ public:
~QSslCertificatePrivate()
{
+#ifndef QT_NO_OPENSSL
if (x509)
q_X509_free(x509);
+#endif
}
bool null;
@@ -89,6 +104,18 @@ public:
QDateTime notValidAfter;
QDateTime notValidBefore;
+#ifdef QT_NO_OPENSSL
+ bool subjectMatchesIssuer;
+ QSsl::KeyAlgorithm publicKeyAlgorithm;
+ QByteArray publicKeyDerData;
+ QMultiMap<QSsl::AlternativeNameEntryType, QString> subjectAlternativeNames;
+ QList<QSslCertificateExtension> extensions;
+
+ QByteArray derData;
+
+ bool parse(const QByteArray &data);
+ bool parseExtension(const QByteArray &data, QSslCertificateExtension *extension);
+#endif
X509 *x509;
void init(const QByteArray &data, QSsl::EncodingFormat format);
@@ -102,12 +129,19 @@ public:
static QList<QSslCertificate> certificatesFromDer(const QByteArray &der, int count = -1);
static bool isBlacklisted(const QSslCertificate &certificate);
static QSslCertificateExtension convertExtension(X509_EXTENSION *ext);
+ static QByteArray subjectInfoToString(QSslCertificate::SubjectInfo info);
friend class QSslSocketBackendPrivate;
QAtomicInt ref;
+
+#ifdef Q_OS_WINRT
+ Microsoft::WRL::ComPtr<ABI::Windows::Security::Cryptography::Certificates::ICertificate> certificate;
+
+ static QSslCertificate QSslCertificate_from_Certificate(ABI::Windows::Security::Cryptography::Certificates::ICertificate *iCertificate);
+#endif
};
QT_END_NAMESPACE
-#endif
+#endif // QSSLCERTIFICATE_OPENSSL_P_H
diff --git a/src/network/ssl/qsslcertificate_qt.cpp b/src/network/ssl/qsslcertificate_qt.cpp
new file mode 100644
index 0000000000..6ea78a408b
--- /dev/null
+++ b/src/network/ssl/qsslcertificate_qt.cpp
@@ -0,0 +1,518 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+
+#include "qsslcertificate.h"
+#include "qsslcertificate_p.h"
+#include "qsslkey.h"
+#include "qsslkey_p.h"
+#include "qsslcertificateextension.h"
+#include "qsslcertificateextension_p.h"
+#include "qasn1element_p.h"
+
+QT_BEGIN_NAMESPACE
+
+enum GeneralNameType
+{
+ Rfc822NameType = 0x81,
+ DnsNameType = 0x82,
+ UniformResourceIdentifierType = 0x86
+};
+
+bool QSslCertificate::operator==(const QSslCertificate &other) const
+{
+ if (d == other.d)
+ return true;
+ if (d->null && other.d->null)
+ return true;
+ return d->derData == other.d->derData;
+}
+
+bool QSslCertificate::isNull() const
+{
+ return d->null;
+}
+
+bool QSslCertificate::isSelfSigned() const
+{
+ if (d->null)
+ return false;
+
+ qWarning("QSslCertificate::isSelfSigned: This function does not check, whether the certificate \
+ is actually signed. It just checks whether issuer and subject are identical");
+ return d->subjectMatchesIssuer;
+}
+
+QByteArray QSslCertificate::version() const
+{
+ return d->versionString;
+}
+
+QByteArray QSslCertificate::serialNumber() const
+{
+ return d->serialNumberString;
+}
+
+QStringList QSslCertificate::issuerInfo(SubjectInfo info) const
+{
+ return issuerInfo(QSslCertificatePrivate::subjectInfoToString(info));
+}
+
+QStringList QSslCertificate::issuerInfo(const QByteArray &attribute) const
+{
+ return d->issuerInfo.values(attribute);
+}
+
+QStringList QSslCertificate::subjectInfo(SubjectInfo info) const
+{
+ return subjectInfo(QSslCertificatePrivate::subjectInfoToString(info));
+}
+
+QStringList QSslCertificate::subjectInfo(const QByteArray &attribute) const
+{
+ return d->subjectInfo.values(attribute);
+}
+
+QList<QByteArray> QSslCertificate::subjectInfoAttributes() const
+{
+ return d->subjectInfo.uniqueKeys();
+}
+
+QList<QByteArray> QSslCertificate::issuerInfoAttributes() const
+{
+ return d->issuerInfo.uniqueKeys();
+}
+
+QMultiMap<QSsl::AlternativeNameEntryType, QString> QSslCertificate::subjectAlternativeNames() const
+{
+ return d->subjectAlternativeNames;
+}
+
+QDateTime QSslCertificate::effectiveDate() const
+{
+ return d->notValidBefore;
+}
+
+QDateTime QSslCertificate::expiryDate() const
+{
+ return d->notValidAfter;
+}
+
+#ifndef Q_OS_WINRT // implemented in qsslcertificate_winrt.cpp
+Qt::HANDLE QSslCertificate::handle() const
+{
+ Q_UNIMPLEMENTED();
+ return 0;
+}
+#endif
+
+QSslKey QSslCertificate::publicKey() const
+{
+ QSslKey key;
+ key.d->type = QSsl::PublicKey;
+ if (d->publicKeyAlgorithm != QSsl::Opaque) {
+ key.d->algorithm = d->publicKeyAlgorithm;
+ key.d->decodeDer(d->publicKeyDerData);
+ }
+ return key;
+}
+
+QList<QSslCertificateExtension> QSslCertificate::extensions() const
+{
+ return d->extensions;
+}
+
+#define BEGINCERTSTRING "-----BEGIN CERTIFICATE-----"
+#define ENDCERTSTRING "-----END CERTIFICATE-----"
+
+QByteArray QSslCertificate::toPem() const
+{
+ QByteArray array = toDer();
+
+ // Convert to Base64 - wrap at 64 characters.
+ array = array.toBase64();
+ QByteArray tmp;
+ for (int i = 0; i <= array.size() - 64; i += 64) {
+ tmp += QByteArray::fromRawData(array.data() + i, 64);
+ tmp += '\n';
+ }
+ if (int remainder = array.size() % 64) {
+ tmp += QByteArray::fromRawData(array.data() + array.size() - remainder, remainder);
+ tmp += '\n';
+ }
+
+ return BEGINCERTSTRING "\n" + tmp + ENDCERTSTRING "\n";
+}
+
+QByteArray QSslCertificate::toDer() const
+{
+ return d->derData;
+}
+
+QString QSslCertificate::toText() const
+{
+ Q_UNIMPLEMENTED();
+ return QString();
+}
+
+void QSslCertificatePrivate::init(const QByteArray &data, QSsl::EncodingFormat format)
+{
+ if (!data.isEmpty()) {
+ QList<QSslCertificate> certs = (format == QSsl::Pem)
+ ? certificatesFromPem(data, 1)
+ : certificatesFromDer(data, 1);
+ if (!certs.isEmpty()) {
+ *this = *certs.first().d;
+ }
+ }
+}
+
+static bool matchLineFeed(const QByteArray &pem, int *offset)
+{
+ char ch = 0;
+
+ // ignore extra whitespace at the end of the line
+ while (*offset < pem.size() && (ch = pem.at(*offset)) == ' ')
+ ++*offset;
+
+ if (ch == '\n') {
+ *offset += 1;
+ return true;
+ }
+ if (ch == '\r' && pem.size() > (*offset + 1) && pem.at(*offset + 1) == '\n') {
+ *offset += 2;
+ return true;
+ }
+ return false;
+}
+
+QList<QSslCertificate> QSslCertificatePrivate::certificatesFromPem(const QByteArray &pem, int count)
+{
+ QList<QSslCertificate> certificates;
+ int offset = 0;
+ while (count == -1 || certificates.size() < count) {
+ int startPos = pem.indexOf(BEGINCERTSTRING, offset);
+ if (startPos == -1)
+ break;
+ startPos += sizeof(BEGINCERTSTRING) - 1;
+ if (!matchLineFeed(pem, &startPos))
+ break;
+
+ int endPos = pem.indexOf(ENDCERTSTRING, startPos);
+ if (endPos == -1)
+ break;
+
+ offset = endPos + sizeof(ENDCERTSTRING) - 1;
+ if (offset < pem.size() && !matchLineFeed(pem, &offset))
+ break;
+
+ QByteArray decoded = QByteArray::fromBase64(
+ QByteArray::fromRawData(pem.data() + startPos, endPos - startPos));
+ certificates << certificatesFromDer(decoded, 1);;
+ }
+
+ return certificates;
+}
+
+QList<QSslCertificate> QSslCertificatePrivate::certificatesFromDer(const QByteArray &der, int count)
+{
+ QList<QSslCertificate> certificates;
+
+ QByteArray data = der;
+ while (count == -1 || certificates.size() < count) {
+ QSslCertificate cert;
+ if (!cert.d->parse(data))
+ break;
+
+ certificates << cert;
+ data.remove(0, cert.d->derData.size());
+ }
+
+ return certificates;
+}
+
+static QByteArray colonSeparatedHex(const QByteArray &value)
+{
+ QByteArray hexString;
+ hexString.reserve(value.size() * 3);
+ for (int a = 0; a < value.size(); ++a) {
+ const quint8 b = value.at(a);
+ if (b || !hexString.isEmpty()) { // skip leading zeros
+ hexString += QByteArray::number(b, 16).rightJustified(2, '0');
+ hexString += ':';
+ }
+ }
+ hexString.chop(1);
+ return hexString;
+}
+
+bool QSslCertificatePrivate::parse(const QByteArray &data)
+{
+ QAsn1Element root;
+
+ QDataStream dataStream(data);
+ if (!root.read(dataStream) || root.type() != QAsn1Element::SequenceType)
+ return false;
+
+ QDataStream rootStream(root.value());
+ QAsn1Element cert;
+ if (!cert.read(rootStream) || cert.type() != QAsn1Element::SequenceType)
+ return false;
+
+ // version or serial number
+ QAsn1Element elem;
+ QDataStream certStream(cert.value());
+ if (!elem.read(certStream))
+ return false;
+
+ if (elem.type() == QAsn1Element::Context0Type) {
+ QDataStream versionStream(elem.value());
+ if (!elem.read(versionStream) || elem.type() != QAsn1Element::IntegerType)
+ return false;
+
+ versionString = QByteArray::number(elem.value()[0] + 1);
+ if (!elem.read(certStream))
+ return false;
+ } else {
+ versionString = QByteArray::number(1);
+ }
+
+ // serial number
+ if (elem.type() != QAsn1Element::IntegerType)
+ return false;
+ serialNumberString = colonSeparatedHex(elem.value());
+
+ // algorithm ID
+ if (!elem.read(certStream) || elem.type() != QAsn1Element::SequenceType)
+ return false;
+
+ // issuer info
+ if (!elem.read(certStream) || elem.type() != QAsn1Element::SequenceType)
+ return false;
+
+ QByteArray issuerDer = data.mid(dataStream.device()->pos() - elem.value().length(), elem.value().length());
+ issuerInfo = elem.toInfo();
+
+ // validity period
+ if (!elem.read(certStream) || elem.type() != QAsn1Element::SequenceType)
+ return false;
+
+ QDataStream validityStream(elem.value());
+ if (!elem.read(validityStream) || (elem.type() != QAsn1Element::UtcTimeType && elem.type() != QAsn1Element::GeneralizedTimeType))
+ return false;
+
+ notValidBefore = elem.toDateTime();
+ if (!elem.read(validityStream) || (elem.type() != QAsn1Element::UtcTimeType && elem.type() != QAsn1Element::GeneralizedTimeType))
+ return false;
+
+ notValidAfter = elem.toDateTime();
+
+ // subject name
+ if (!elem.read(certStream) || elem.type() != QAsn1Element::SequenceType)
+ return false;
+
+ QByteArray subjectDer = data.mid(dataStream.device()->pos() - elem.value().length(), elem.value().length());
+ subjectInfo = elem.toInfo();
+ subjectMatchesIssuer = issuerDer == subjectDer;
+
+ // public key
+ qint64 keyStart = certStream.device()->pos();
+ if (!elem.read(certStream) || elem.type() != QAsn1Element::SequenceType)
+ return false;
+
+ publicKeyDerData.resize(certStream.device()->pos() - keyStart);
+ QDataStream keyStream(elem.value());
+ if (!elem.read(keyStream) || elem.type() != QAsn1Element::SequenceType)
+ return false;
+
+
+ // key algorithm
+ if (!elem.read(elem.value()) || elem.type() != QAsn1Element::ObjectIdentifierType)
+ return false;
+
+ const QByteArray oid = elem.toObjectId();
+ if (oid == RSA_ENCRYPTION_OID)
+ publicKeyAlgorithm = QSsl::Rsa;
+ else if (oid == RSA_ENCRYPTION_OID)
+ publicKeyAlgorithm = QSsl::Dsa;
+ else
+ publicKeyAlgorithm = QSsl::Opaque;
+
+ certStream.device()->seek(keyStart);
+ certStream.readRawData(publicKeyDerData.data(), publicKeyDerData.size());
+
+ // extensions
+ while (elem.read(certStream)) {
+ if (elem.type() == QAsn1Element::Context3Type) {
+ if (elem.read(elem.value()) && elem.type() == QAsn1Element::SequenceType) {
+ QDataStream extStream(elem.value());
+ while (elem.read(extStream) && elem.type() == QAsn1Element::SequenceType) {
+ QSslCertificateExtension extension;
+ if (!parseExtension(elem.value(), &extension))
+ return false;
+ extensions << extension;
+
+ if (extension.oid() == QLatin1String("2.5.29.17")) {
+ // subjectAltName
+ QAsn1Element sanElem;
+ if (sanElem.read(extension.value().toByteArray()) && sanElem.type() == QAsn1Element::SequenceType) {
+ QDataStream nameStream(sanElem.value());
+ QAsn1Element nameElem;
+ while (nameElem.read(nameStream)) {
+ if (nameElem.type() == Rfc822NameType) {
+ subjectAlternativeNames.insert(QSsl::EmailEntry, QString::fromLatin1(nameElem.value(), nameElem.value().size()));
+ } else if (nameElem.type() == DnsNameType) {
+ subjectAlternativeNames.insert(QSsl::DnsEntry, QString::fromLatin1(nameElem.value(), nameElem.value().size()));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ derData = data.left(dataStream.device()->pos());
+ null = false;
+ return true;
+}
+
+bool QSslCertificatePrivate::parseExtension(const QByteArray &data, QSslCertificateExtension *extension)
+{
+ bool ok;
+ bool critical = false;
+ QAsn1Element oidElem, valElem;
+
+ QDataStream seqStream(data);
+
+ // oid
+ if (!oidElem.read(seqStream) || oidElem.type() != QAsn1Element::ObjectIdentifierType)
+ return false;
+ const QByteArray oid = oidElem.toObjectId();
+
+ // critical and value
+ if (!valElem.read(seqStream))
+ return false;
+ if (valElem.type() == QAsn1Element::BooleanType) {
+ critical = valElem.toBool(&ok);
+ if (!ok || !valElem.read(seqStream))
+ return false;
+ }
+ if (valElem.type() != QAsn1Element::OctetStringType)
+ return false;
+
+ // interpret value
+ QAsn1Element val;
+ bool supported = true;
+ QVariant value;
+ if (oid == QByteArrayLiteral("1.3.6.1.5.5.7.1.1")) {
+ // authorityInfoAccess
+ if (!val.read(valElem.value()) || val.type() != QAsn1Element::SequenceType)
+ return false;
+ QVariantMap result;
+ foreach (const QAsn1Element &el, val.toVector()) {
+ QVector<QAsn1Element> items = el.toVector();
+ if (items.size() != 2)
+ return false;
+ const QString key = QString::fromLatin1(items.at(0).toObjectName());
+ switch (items.at(1).type()) {
+ case Rfc822NameType:
+ case DnsNameType:
+ case UniformResourceIdentifierType:
+ result[key] = QString::fromLatin1(items.at(1).value(), items.at(1).value().size());
+ break;
+ }
+ }
+ value = result;
+ } else if (oid == QByteArrayLiteral("2.5.29.14")) {
+ // subjectKeyIdentifier
+ if (!val.read(valElem.value()) || val.type() != QAsn1Element::OctetStringType)
+ return false;
+ value = colonSeparatedHex(val.value()).toUpper();
+ } else if (oid == QByteArrayLiteral("2.5.29.19")) {
+ // basicConstraints
+ if (!val.read(valElem.value()) || val.type() != QAsn1Element::SequenceType)
+ return false;
+
+ QVariantMap result;
+ QVector<QAsn1Element> items = val.toVector();
+ if (items.size() > 0) {
+ result[QStringLiteral("ca")] = items.at(0).toBool(&ok);
+ if (!ok)
+ return false;
+ } else {
+ result[QStringLiteral("ca")] = false;
+ }
+ if (items.size() > 1) {
+ result[QStringLiteral("pathLenConstraint")] = items.at(1).toInteger(&ok);
+ if (!ok)
+ return false;
+ }
+ value = result;
+ } else if (oid == QByteArrayLiteral("2.5.29.35")) {
+ // authorityKeyIdentifier
+ if (!val.read(valElem.value()) || val.type() != QAsn1Element::SequenceType)
+ return false;
+ QVariantMap result;
+ foreach (const QAsn1Element &el, val.toVector()) {
+ if (el.type() == 0x80) {
+ result[QStringLiteral("keyid")] = el.value().toHex();
+ } else if (el.type() == 0x82) {
+ result[QStringLiteral("serial")] = colonSeparatedHex(el.value());
+ }
+ }
+ value = result;
+ } else {
+ supported = false;
+ value = valElem.value();
+ }
+
+ extension->d->critical = critical;
+ extension->d->supported = supported;
+ extension->d->oid = QString::fromLatin1(oid);
+ extension->d->name = QString::fromLatin1(oidElem.toObjectName());
+ extension->d->value = value;
+
+ return true;
+}
+
+QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslcertificate_winrt.cpp b/src/network/ssl/qsslcertificate_winrt.cpp
new file mode 100644
index 0000000000..6f4bb80cf9
--- /dev/null
+++ b/src/network/ssl/qsslcertificate_winrt.cpp
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsslcertificate_p.h"
+
+#include <QtCore/qfunctions_winrt.h>
+
+#include <wrl.h>
+#include <windows.storage.streams.h>
+#include <windows.security.cryptography.h>
+#include <robuffer.h>
+
+using namespace Microsoft::WRL;
+using namespace Microsoft::WRL::Wrappers;
+using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::Security::Cryptography;
+using namespace ABI::Windows::Security::Cryptography::Certificates;
+using namespace ABI::Windows::Storage::Streams;
+
+QT_USE_NAMESPACE
+
+struct SslCertificateGlobal
+{
+ SslCertificateGlobal() {
+ HRESULT hr;
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Security_Cryptography_Certificates_Certificate).Get(),
+ &certificateFactory);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Security_Cryptography_CryptographicBuffer).Get(),
+ &bufferFactory);
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+
+ ComPtr<ICertificateFactory> certificateFactory;
+ ComPtr<ICryptographicBufferStatics> bufferFactory;
+};
+Q_GLOBAL_STATIC(SslCertificateGlobal, g)
+
+QSslCertificate QSslCertificatePrivate::QSslCertificate_from_Certificate(ICertificate *iCertificate)
+{
+ Q_ASSERT(iCertificate);
+ ComPtr<IBuffer> buffer;
+ HRESULT hr = iCertificate->GetCertificateBlob(&buffer);
+ RETURN_IF_FAILED("Could not obtain certification blob", return QSslCertificate());
+ ComPtr<Windows::Storage::Streams::IBufferByteAccess> byteAccess;
+ hr = buffer.As(&byteAccess);
+ RETURN_IF_FAILED("Could not obtain byte access to buffer", return QSslCertificate());
+ char *data;
+ hr = byteAccess->Buffer(reinterpret_cast<byte **>(&data));
+ RETURN_IF_FAILED("Could not obtain buffer data", return QSslCertificate());
+ UINT32 size;
+ hr = buffer->get_Length(&size);
+ RETURN_IF_FAILED("Could not obtain buffer length ", return QSslCertificate());
+ QByteArray der(data, size);
+
+ QSslCertificate certificate;
+ certificate.d->null = false;
+ certificate.d->certificate = iCertificate;
+
+ return certificatesFromDer(der, 1).at(0);
+}
+
+Qt::HANDLE QSslCertificate::handle() const
+{
+ if (!d->certificate) {
+ HRESULT hr;
+ ComPtr<IBuffer> buffer;
+ hr = g->bufferFactory->CreateFromByteArray(d->derData.length(), (BYTE *)d->derData.data(), &buffer);
+ RETURN_IF_FAILED("Failed to create the certificate data buffer", return 0);
+
+ hr = g->certificateFactory->CreateCertificate(buffer.Get(), &d->certificate);
+ RETURN_IF_FAILED("Failed to create the certificate handle from the data buffer", return 0);
+ }
+
+ return d->certificate.Get();
+}
diff --git a/src/network/ssl/qsslconfiguration.cpp b/src/network/ssl/qsslconfiguration.cpp
index 14881931af..64b75f98ec 100644
--- a/src/network/ssl/qsslconfiguration.cpp
+++ b/src/network/ssl/qsslconfiguration.cpp
@@ -208,6 +208,7 @@ bool QSslConfiguration::operator==(const QSslConfiguration &other) const
d->localCertificateChain == other.d->localCertificateChain &&
d->privateKey == other.d->privateKey &&
d->sessionCipher == other.d->sessionCipher &&
+ d->sessionProtocol == other.d->sessionProtocol &&
d->ciphers == other.d->ciphers &&
d->caCertificates == other.d->caCertificates &&
d->protocol == other.d->protocol &&
@@ -512,6 +513,18 @@ QSslCipher QSslConfiguration::sessionCipher() const
}
/*!
+ Returns the socket's SSL/TLS protocol or UnknownProtocol if the
+ connection isn't encrypted. The socket's protocol for the session
+ is set during the handshake phase.
+
+ \sa protocol(), setProtocol()
+*/
+QSsl::SslProtocol QSslConfiguration::sessionProtocol() const
+{
+ return d->sessionProtocol;
+}
+
+/*!
Returns the \l {QSslKey} {SSL key} assigned to this connection or
a null key if none has been assigned yet.
diff --git a/src/network/ssl/qsslconfiguration.h b/src/network/ssl/qsslconfiguration.h
index 587187ca06..4c5799bf28 100644
--- a/src/network/ssl/qsslconfiguration.h
+++ b/src/network/ssl/qsslconfiguration.h
@@ -109,6 +109,7 @@ public:
QSslCertificate peerCertificate() const;
QList<QSslCertificate> peerCertificateChain() const;
QSslCipher sessionCipher() const;
+ QSsl::SslProtocol sessionProtocol() const;
// Private keys, for server sockets
QSslKey privateKey() const;
diff --git a/src/network/ssl/qsslconfiguration_p.h b/src/network/ssl/qsslconfiguration_p.h
index d183c3335c..29bd4053ad 100644
--- a/src/network/ssl/qsslconfiguration_p.h
+++ b/src/network/ssl/qsslconfiguration_p.h
@@ -81,7 +81,8 @@ class QSslConfigurationPrivate: public QSharedData
{
public:
QSslConfigurationPrivate()
- : protocol(QSsl::SecureProtocols),
+ : sessionProtocol(QSsl::UnknownProtocol),
+ protocol(QSsl::SecureProtocols),
peerVerifyMode(QSslSocket::AutoVerifyPeer),
peerVerifyDepth(0),
allowRootCertOnDemandLoading(true),
@@ -98,6 +99,7 @@ public:
QSslKey privateKey;
QSslCipher sessionCipher;
+ QSsl::SslProtocol sessionProtocol;
QList<QSslCipher> ciphers;
QList<QSslCertificate> caCertificates;
diff --git a/src/network/ssl/qsslcontext.cpp b/src/network/ssl/qsslcontext_openssl.cpp
index addf7a2ff5..0ca14f199e 100644
--- a/src/network/ssl/qsslcontext.cpp
+++ b/src/network/ssl/qsslcontext_openssl.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
** Contact: http://www.qt-project.org/legal
**
@@ -44,7 +44,7 @@
#include <QtNetwork/qsslsocket.h>
#include <QtCore/qmutex.h>
-#include "private/qsslcontext_p.h"
+#include "private/qsslcontext_openssl_p.h"
#include "private/qsslsocket_p.h"
#include "private/qsslsocket_openssl_p.h"
#include "private/qsslsocket_openssl_symbols_p.h"
diff --git a/src/network/ssl/qsslcontext_p.h b/src/network/ssl/qsslcontext_openssl_p.h
index 408376b954..d4ab91f8ec 100644
--- a/src/network/ssl/qsslcontext_p.h
+++ b/src/network/ssl/qsslcontext_openssl_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
** Contact: http://www.qt-project.org/legal
**
@@ -41,8 +41,8 @@
****************************************************************************/
-#ifndef QSSLCONTEXT_H
-#define QSSLCONTEXT_H
+#ifndef QSSLCONTEXT_OPENSSL_P_H
+#define QSSLCONTEXT_OPENSSL_P_H
//
// W A R N I N G
@@ -121,4 +121,4 @@ private:
QT_END_NAMESPACE
-#endif // QSSLCONTEXT_H
+#endif // QSSLCONTEXT_OPENSSL_P_H
diff --git a/src/network/ssl/qsslkey.h b/src/network/ssl/qsslkey.h
index 145d4a28f1..59063e2e57 100644
--- a/src/network/ssl/qsslkey.h
+++ b/src/network/ssl/qsslkey.h
@@ -95,6 +95,7 @@ public:
private:
QExplicitlySharedDataPointer<QSslKeyPrivate> d;
friend class QSslCertificate;
+ friend class QSslSocketBackendPrivate;
};
Q_DECLARE_SHARED(QSslKey)
diff --git a/src/network/ssl/qsslkey_openssl.cpp b/src/network/ssl/qsslkey_openssl.cpp
new file mode 100644
index 0000000000..6b0fa954eb
--- /dev/null
+++ b/src/network/ssl/qsslkey_openssl.cpp
@@ -0,0 +1,224 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qsslkey.h"
+#include "qsslkey_p.h"
+#include "qsslsocket_openssl_symbols_p.h"
+#include "qsslsocket.h"
+#include "qsslsocket_p.h"
+
+#include <QtCore/qatomic.h>
+#include <QtCore/qbytearray.h>
+#include <QtCore/qiodevice.h>
+#ifndef QT_NO_DEBUG_STREAM
+#include <QtCore/qdebug.h>
+#endif
+
+QT_BEGIN_NAMESPACE
+
+void QSslKeyPrivate::clear(bool deep)
+{
+ isNull = true;
+ if (!QSslSocket::supportsSsl())
+ return;
+ if (rsa) {
+ if (deep)
+ q_RSA_free(rsa);
+ rsa = 0;
+ }
+ if (dsa) {
+ if (deep)
+ q_DSA_free(dsa);
+ dsa = 0;
+ }
+ if (opaque) {
+ if (deep)
+ q_EVP_PKEY_free(opaque);
+ opaque = 0;
+ }
+}
+
+bool QSslKeyPrivate::fromEVP_PKEY(EVP_PKEY *pkey)
+{
+ if (pkey->type == EVP_PKEY_RSA) {
+ isNull = false;
+ algorithm = QSsl::Rsa;
+ type = QSsl::PrivateKey;
+
+ rsa = q_RSA_new();
+ memcpy(rsa, q_EVP_PKEY_get1_RSA(pkey), sizeof(RSA));
+
+ return true;
+ }
+ else if (pkey->type == EVP_PKEY_DSA) {
+ isNull = false;
+ algorithm = QSsl::Dsa;
+ type = QSsl::PrivateKey;
+
+ dsa = q_DSA_new();
+ memcpy(rsa, q_EVP_PKEY_get1_DSA(pkey), sizeof(DSA));
+
+ return true;
+ }
+ else {
+ // Unknown key type. This could be handled as opaque, but then
+ // we'd eventually leak memory since we wouldn't be able to free
+ // the underlying EVP_PKEY structure. For now, we won't support
+ // this.
+ }
+
+ return false;
+}
+
+void QSslKeyPrivate::decodeDer(const QByteArray &der, bool deepClear)
+{
+ QMap<QByteArray, QByteArray> headers;
+ decodePem(pemFromDer(der, headers), QByteArray(), deepClear);
+}
+
+void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase,
+ bool deepClear)
+{
+ if (pem.isEmpty())
+ return;
+
+ clear(deepClear);
+
+ if (!QSslSocket::supportsSsl())
+ return;
+
+ BIO *bio = q_BIO_new_mem_buf(const_cast<char *>(pem.data()), pem.size());
+ if (!bio)
+ return;
+
+ void *phrase = (void *)passPhrase.constData();
+
+ if (algorithm == QSsl::Rsa) {
+ RSA *result = (type == QSsl::PublicKey)
+ ? q_PEM_read_bio_RSA_PUBKEY(bio, &rsa, 0, phrase)
+ : q_PEM_read_bio_RSAPrivateKey(bio, &rsa, 0, phrase);
+ if (rsa && rsa == result)
+ isNull = false;
+ } else {
+ DSA *result = (type == QSsl::PublicKey)
+ ? q_PEM_read_bio_DSA_PUBKEY(bio, &dsa, 0, phrase)
+ : q_PEM_read_bio_DSAPrivateKey(bio, &dsa, 0, phrase);
+ if (dsa && dsa == result)
+ isNull = false;
+ }
+
+ q_BIO_free(bio);
+}
+
+int QSslKeyPrivate::length() const
+{
+ if (isNull || algorithm == QSsl::Opaque)
+ return -1;
+
+ return (algorithm == QSsl::Rsa)
+ ? q_BN_num_bits(rsa->n) : q_BN_num_bits(dsa->p);
+}
+
+QByteArray QSslKeyPrivate::toPem(const QByteArray &passPhrase) const
+{
+ if (!QSslSocket::supportsSsl() || isNull || algorithm == QSsl::Opaque)
+ return QByteArray();
+
+ BIO *bio = q_BIO_new(q_BIO_s_mem());
+ if (!bio)
+ return QByteArray();
+
+ bool fail = false;
+
+ if (algorithm == QSsl::Rsa) {
+ if (type == QSsl::PublicKey) {
+ if (!q_PEM_write_bio_RSA_PUBKEY(bio, rsa))
+ fail = true;
+ } else {
+ if (!q_PEM_write_bio_RSAPrivateKey(
+ bio, rsa,
+ // ### the cipher should be selectable in the API:
+ passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(),
+ (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) {
+ fail = true;
+ }
+ }
+ } else {
+ if (type == QSsl::PublicKey) {
+ if (!q_PEM_write_bio_DSA_PUBKEY(bio, dsa))
+ fail = true;
+ } else {
+ if (!q_PEM_write_bio_DSAPrivateKey(
+ bio, dsa,
+ // ### the cipher should be selectable in the API:
+ passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(),
+ (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) {
+ fail = true;
+ }
+ }
+ }
+
+ QByteArray pem;
+ if (!fail) {
+ char *data;
+ long size = q_BIO_get_mem_data(bio, &data);
+ pem = QByteArray(data, size);
+ }
+ q_BIO_free(bio);
+ return pem;
+}
+
+Qt::HANDLE QSslKeyPrivate::handle() const
+{
+ switch (algorithm) {
+ case QSsl::Opaque:
+ return Qt::HANDLE(opaque);
+ case QSsl::Rsa:
+ return Qt::HANDLE(rsa);
+ case QSsl::Dsa:
+ return Qt::HANDLE(dsa);
+ default:
+ return Qt::HANDLE(NULL);
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslkey.cpp b/src/network/ssl/qsslkey_p.cpp
index 95eed6e4b3..b051ec6874 100644
--- a/src/network/ssl/qsslkey.cpp
+++ b/src/network/ssl/qsslkey_p.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -58,12 +58,12 @@
#include "qsslkey.h"
#include "qsslkey_p.h"
-#include "qsslsocket_openssl_symbols_p.h"
#include "qsslsocket.h"
#include "qsslsocket_p.h"
#include <QtCore/qatomic.h>
#include <QtCore/qbytearray.h>
+#include <QtCore/qbytearraymatcher.h>
#include <QtCore/qiodevice.h>
#ifndef QT_NO_DEBUG_STREAM
#include <QtCore/qdebug.h>
@@ -72,31 +72,13 @@
QT_BEGIN_NAMESPACE
/*!
+ \fn void QSslKeyPrivate::clear(bool deep)
\internal
*/
-void QSslKeyPrivate::clear(bool deep)
-{
- isNull = true;
- if (!QSslSocket::supportsSsl())
- return;
- if (rsa) {
- if (deep)
- q_RSA_free(rsa);
- rsa = 0;
- }
- if (dsa) {
- if (deep)
- q_DSA_free(dsa);
- dsa = 0;
- }
- if (opaque) {
- if (deep)
- q_EVP_PKEY_free(opaque);
- opaque = 0;
- }
-}
/*!
+ \fn void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase,
+ bool deepClear)
\internal
Allocates a new rsa or dsa struct and decodes \a pem into it
@@ -109,39 +91,6 @@ void QSslKeyPrivate::clear(bool deep)
If \a passPhrase is non-empty, it will be used for decrypting
\a pem.
*/
-void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase,
- bool deepClear)
-{
- if (pem.isEmpty())
- return;
-
- clear(deepClear);
-
- if (!QSslSocket::supportsSsl())
- return;
-
- BIO *bio = q_BIO_new_mem_buf(const_cast<char *>(pem.data()), pem.size());
- if (!bio)
- return;
-
- void *phrase = (void *)passPhrase.constData();
-
- if (algorithm == QSsl::Rsa) {
- RSA *result = (type == QSsl::PublicKey)
- ? q_PEM_read_bio_RSA_PUBKEY(bio, &rsa, 0, phrase)
- : q_PEM_read_bio_RSAPrivateKey(bio, &rsa, 0, phrase);
- if (rsa && rsa == result)
- isNull = false;
- } else {
- DSA *result = (type == QSsl::PublicKey)
- ? q_PEM_read_bio_DSA_PUBKEY(bio, &dsa, 0, phrase)
- : q_PEM_read_bio_DSAPrivateKey(bio, &dsa, 0, phrase);
- if (dsa && dsa == result)
- isNull = false;
- }
-
- q_BIO_free(bio);
-}
/*!
Constructs a null key.
@@ -158,12 +107,11 @@ QSslKey::QSslKey()
*/
QByteArray QSslKeyPrivate::pemHeader() const
{
- // ### use QByteArray::fromRawData() instead
if (type == QSsl::PublicKey)
- return QByteArray("-----BEGIN PUBLIC KEY-----\n");
+ return QByteArrayLiteral("-----BEGIN PUBLIC KEY-----");
else if (algorithm == QSsl::Rsa)
- return QByteArray("-----BEGIN RSA PRIVATE KEY-----\n");
- return QByteArray("-----BEGIN DSA PRIVATE KEY-----\n");
+ return QByteArrayLiteral("-----BEGIN RSA PRIVATE KEY-----");
+ return QByteArrayLiteral("-----BEGIN DSA PRIVATE KEY-----");
}
/*!
@@ -171,12 +119,11 @@ QByteArray QSslKeyPrivate::pemHeader() const
*/
QByteArray QSslKeyPrivate::pemFooter() const
{
- // ### use QByteArray::fromRawData() instead
if (type == QSsl::PublicKey)
- return QByteArray("-----END PUBLIC KEY-----\n");
+ return QByteArrayLiteral("-----END PUBLIC KEY-----");
else if (algorithm == QSsl::Rsa)
- return QByteArray("-----END RSA PRIVATE KEY-----\n");
- return QByteArray("-----END DSA PRIVATE KEY-----\n");
+ return QByteArrayLiteral("-----END RSA PRIVATE KEY-----");
+ return QByteArrayLiteral("-----END DSA PRIVATE KEY-----");
}
/*!
@@ -184,7 +131,7 @@ QByteArray QSslKeyPrivate::pemFooter() const
Returns a DER key formatted as PEM.
*/
-QByteArray QSslKeyPrivate::pemFromDer(const QByteArray &der) const
+QByteArray QSslKeyPrivate::pemFromDer(const QByteArray &der, const QMap<QByteArray, QByteArray> &headers) const
{
QByteArray pem(der.toBase64());
@@ -198,8 +145,17 @@ QByteArray QSslKeyPrivate::pemFromDer(const QByteArray &der) const
if (rem)
pem.append('\n'); // ###
- pem.prepend(pemHeader());
- pem.append(pemFooter());
+ QByteArray extra;
+ if (!headers.isEmpty()) {
+ QMap<QByteArray, QByteArray>::const_iterator it = headers.constEnd();
+ do {
+ it--;
+ extra += it.key() + ": " + it.value() + '\n';
+ } while (it != headers.constBegin());
+ extra += '\n';
+ }
+ pem.prepend(pemHeader() + '\n' + extra);
+ pem.append(pemFooter() + '\n');
return pem;
}
@@ -209,7 +165,7 @@ QByteArray QSslKeyPrivate::pemFromDer(const QByteArray &der) const
Returns a PEM key formatted as DER.
*/
-QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem) const
+QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem, QMap<QByteArray, QByteArray> *headers) const
{
const QByteArray header = pemHeader();
const QByteArray footer = pemFooter();
@@ -223,14 +179,49 @@ QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem) const
der = der.mid(headerIndex + header.size(), footerIndex - (headerIndex + header.size()));
+ if (der.contains("Proc-Type:")) {
+ // taken from QHttpNetworkReplyPrivate::parseHeader
+ const QByteArrayMatcher lf("\n");
+ const QByteArrayMatcher colon(":");
+ int i = 0;
+ while (i < der.count()) {
+ int j = colon.indexIn(der, i); // field-name
+ if (j == -1)
+ break;
+ const QByteArray field = der.mid(i, j - i).trimmed();
+ j++;
+ // any number of LWS is allowed before and after the value
+ QByteArray value;
+ do {
+ i = lf.indexIn(der, j);
+ if (i == -1)
+ break;
+ if (!value.isEmpty())
+ value += ' ';
+ // check if we have CRLF or only LF
+ bool hasCR = (i && der[i-1] == '\r');
+ int length = i -(hasCR ? 1: 0) - j;
+ value += der.mid(j, length).trimmed();
+ j = ++i;
+ } while (i < der.count() && (der.at(i) == ' ' || der.at(i) == '\t'));
+ if (i == -1)
+ break; // something is wrong
+
+ headers->insert(field, value);
+ }
+ der = der.mid(i);
+ }
+
return QByteArray::fromBase64(der); // ignores newlines
}
/*!
Constructs a QSslKey by decoding the string in the byte array
\a encoded using a specified \a algorithm and \a encoding format.
- If the encoded key is encrypted, \a passPhrase is used to decrypt
- it. \a type specifies whether the key is public or private.
+ \a type specifies whether the key is public or private.
+
+ If the key is encoded as PEM and encrypted, \a passPhrase is used
+ to decrypt it.
After construction, use isNull() to check if \a encoded contained
a valid key.
@@ -241,16 +232,19 @@ QSslKey::QSslKey(const QByteArray &encoded, QSsl::KeyAlgorithm algorithm,
{
d->type = type;
d->algorithm = algorithm;
- d->decodePem((encoding == QSsl::Der)
- ? d->pemFromDer(encoded) : encoded,
- passPhrase);
+ if (encoding == QSsl::Der)
+ d->decodeDer(encoded);
+ else
+ d->decodePem(encoded, passPhrase);
}
/*!
Constructs a QSslKey by reading and decoding data from a
\a device using a specified \a algorithm and \a encoding format.
- If the encoded key is encrypted, \a passPhrase is used to decrypt
- it. \a type specifies whether the key is public or private.
+ \a type specifies whether the key is public or private.
+
+ If the key is encoded as PEM and encrypted, \a passPhrase is used
+ to decrypt it.
After construction, use isNull() to check if \a device provided
a valid key.
@@ -264,9 +258,10 @@ QSslKey::QSslKey(QIODevice *device, QSsl::KeyAlgorithm algorithm, QSsl::Encoding
encoded = device->readAll();
d->type = type;
d->algorithm = algorithm;
- d->decodePem((encoding == QSsl::Der) ?
- d->pemFromDer(encoded) : encoded,
- passPhrase);
+ if (encoding == QSsl::Der)
+ d->decodeDer(encoded);
+ else
+ d->decodePem(encoded, passPhrase);
}
/*!
@@ -281,7 +276,11 @@ QSslKey::QSslKey(QIODevice *device, QSsl::KeyAlgorithm algorithm, QSsl::Encoding
QSslKey::QSslKey(Qt::HANDLE handle, QSsl::KeyType type)
: d(new QSslKeyPrivate)
{
+#ifndef QT_NO_OPENSSL
d->opaque = reinterpret_cast<EVP_PKEY *>(handle);
+#else
+ d->opaque = handle;
+#endif
d->algorithm = QSsl::Opaque;
d->type = type;
d->isNull = !d->opaque;
@@ -346,11 +345,7 @@ void QSslKey::clear()
*/
int QSslKey::length() const
{
- if (d->isNull || d->algorithm == QSsl::Opaque)
- return -1;
-
- return (d->algorithm == QSsl::Rsa)
- ? q_BN_num_bits(d->rsa->n) : q_BN_num_bits(d->dsa->p);
+ return d->length();
}
/*!
@@ -370,17 +365,26 @@ QSsl::KeyAlgorithm QSslKey::algorithm() const
}
/*!
- Returns the key in DER encoding. The result is encrypted with
- \a passPhrase if the key is a private key and \a passPhrase is
- non-empty.
+ Returns the key in DER encoding.
+
+ The \a passPhrase argument should be omitted as DER cannot be
+ encrypted. It will be removed in a future version of Qt.
*/
-// ### autotest failure for non-empty passPhrase and private key
QByteArray QSslKey::toDer(const QByteArray &passPhrase) const
{
if (d->isNull || d->algorithm == QSsl::Opaque)
return QByteArray();
- return d->derFromPem(toPem(passPhrase));
+ // Encrypted DER is nonsense, see QTBUG-41038.
+ if (d->type == QSsl::PrivateKey && !passPhrase.isEmpty())
+ return QByteArray();
+
+#ifndef QT_NO_OPENSSL
+ QMap<QByteArray, QByteArray> headers;
+ return d->derFromPem(toPem(passPhrase), &headers);
+#else
+ return d->derData;
+#endif
}
/*!
@@ -390,51 +394,7 @@ QByteArray QSslKey::toDer(const QByteArray &passPhrase) const
*/
QByteArray QSslKey::toPem(const QByteArray &passPhrase) const
{
- if (!QSslSocket::supportsSsl() || d->isNull || d->algorithm == QSsl::Opaque)
- return QByteArray();
-
- BIO *bio = q_BIO_new(q_BIO_s_mem());
- if (!bio)
- return QByteArray();
-
- bool fail = false;
-
- if (d->algorithm == QSsl::Rsa) {
- if (d->type == QSsl::PublicKey) {
- if (!q_PEM_write_bio_RSA_PUBKEY(bio, d->rsa))
- fail = true;
- } else {
- if (!q_PEM_write_bio_RSAPrivateKey(
- bio, d->rsa,
- // ### the cipher should be selectable in the API:
- passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(),
- (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) {
- fail = true;
- }
- }
- } else {
- if (d->type == QSsl::PublicKey) {
- if (!q_PEM_write_bio_DSA_PUBKEY(bio, d->dsa))
- fail = true;
- } else {
- if (!q_PEM_write_bio_DSAPrivateKey(
- bio, d->dsa,
- // ### the cipher should be selectable in the API:
- passPhrase.isEmpty() ? (const EVP_CIPHER *)0 : q_EVP_des_ede3_cbc(),
- (uchar *)passPhrase.data(), passPhrase.size(), 0, 0)) {
- fail = true;
- }
- }
- }
-
- QByteArray pem;
- if (!fail) {
- char *data;
- long size = q_BIO_get_mem_data(bio, &data);
- pem = QByteArray(data, size);
- }
- q_BIO_free(bio);
- return pem;
+ return d->toPem(passPhrase);
}
/*!
@@ -450,16 +410,7 @@ QByteArray QSslKey::toPem(const QByteArray &passPhrase) const
*/
Qt::HANDLE QSslKey::handle() const
{
- switch (d->algorithm) {
- case QSsl::Opaque:
- return Qt::HANDLE(d->opaque);
- case QSsl::Rsa:
- return Qt::HANDLE(d->rsa);
- case QSsl::Dsa:
- return Qt::HANDLE(d->dsa);
- default:
- return Qt::HANDLE(NULL);
- }
+ return d->handle();
}
/*!
diff --git a/src/network/ssl/qsslkey_p.h b/src/network/ssl/qsslkey_p.h
index 54d12d76fb..d24606e6a6 100644
--- a/src/network/ssl/qsslkey_p.h
+++ b/src/network/ssl/qsslkey_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
@@ -40,8 +40,8 @@
****************************************************************************/
-#ifndef QSSLKEY_P_H
-#define QSSLKEY_P_H
+#ifndef QSSLKEY_OPENSSL_P_H
+#define QSSLKEY_OPENSSL_P_H
#include "qsslkey.h"
@@ -58,8 +58,10 @@
#include "qsslsocket_p.h" // includes wincrypt.h
+#ifndef QT_NO_OPENSSL
#include <openssl/rsa.h>
#include <openssl/dsa.h>
+#endif
QT_BEGIN_NAMESPACE
@@ -67,9 +69,11 @@ class QSslKeyPrivate
{
public:
inline QSslKeyPrivate()
- : rsa(0)
+ : opaque(0)
+#ifndef QT_NO_OPENSSL
+ , rsa(0)
, dsa(0)
- , opaque(0)
+#endif
{
clear();
}
@@ -79,19 +83,42 @@ public:
void clear(bool deep = true);
+#ifndef QT_NO_OPENSSL
+ bool fromEVP_PKEY(EVP_PKEY *pkey);
+#endif
+ void decodeDer(const QByteArray &der, bool deepClear = true);
void decodePem(const QByteArray &pem, const QByteArray &passPhrase,
bool deepClear = true);
QByteArray pemHeader() const;
QByteArray pemFooter() const;
- QByteArray pemFromDer(const QByteArray &der) const;
- QByteArray derFromPem(const QByteArray &pem) const;
+ QByteArray pemFromDer(const QByteArray &der, const QMap<QByteArray, QByteArray> &headers) const;
+ QByteArray derFromPem(const QByteArray &pem, QMap<QByteArray, QByteArray> *headers) const;
+
+ int length() const;
+ QByteArray toPem(const QByteArray &passPhrase) const;
+ Qt::HANDLE handle() const;
bool isNull;
QSsl::KeyType type;
QSsl::KeyAlgorithm algorithm;
+#ifndef QT_NO_OPENSSL
+ EVP_PKEY *opaque;
RSA *rsa;
DSA *dsa;
- EVP_PKEY *opaque;
+#else
+ enum Cipher {
+ DesCbc,
+ DesEde3Cbc,
+ Rc2Cbc
+ };
+
+ Q_AUTOTEST_EXPORT static QByteArray decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
+ Q_AUTOTEST_EXPORT static QByteArray encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv);
+
+ Qt::HANDLE opaque;
+ QByteArray derData;
+ int keyLength;
+#endif
QAtomicInt ref;
@@ -101,4 +128,4 @@ private:
QT_END_NAMESPACE
-#endif // QSSLKEY_P_H
+#endif // QSSLKEY_OPENSSL_P_H
diff --git a/src/network/ssl/qsslkey_qt.cpp b/src/network/ssl/qsslkey_qt.cpp
new file mode 100644
index 0000000000..bc1ebc3c08
--- /dev/null
+++ b/src/network/ssl/qsslkey_qt.cpp
@@ -0,0 +1,246 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Jeremy Lainé <jeremy.laine@m4x.org>
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsslkey.h"
+#include "qsslkey_p.h"
+#include "qasn1element_p.h"
+
+#include <QtCore/qcryptographichash.h>
+
+QT_USE_NAMESPACE
+
+static const quint8 bits_table[256] = {
+ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+};
+
+static int numberOfBits(const QByteArray &modulus)
+{
+ int bits = modulus.size() * 8;
+ for (int i = 0; i < modulus.size(); ++i) {
+ quint8 b = modulus[i];
+ bits -= 8;
+ if (b != 0) {
+ bits += bits_table[b];
+ break;
+ }
+ }
+ return bits;
+}
+
+static QByteArray deriveKey(QSslKeyPrivate::Cipher cipher, const QByteArray &passPhrase, const QByteArray &iv)
+{
+ QByteArray key;
+ QCryptographicHash hash(QCryptographicHash::Md5);
+ hash.addData(passPhrase);
+ hash.addData(iv);
+ switch (cipher) {
+ case QSslKeyPrivate::DesCbc:
+ key = hash.result().left(8);
+ break;
+ case QSslKeyPrivate::DesEde3Cbc:
+ key = hash.result();
+ hash.reset();
+ hash.addData(key);
+ hash.addData(passPhrase);
+ hash.addData(iv);
+ key += hash.result().left(8);
+ break;
+ case QSslKeyPrivate::Rc2Cbc:
+ key = hash.result();
+ break;
+ }
+ return key;
+}
+
+void QSslKeyPrivate::clear(bool deep)
+{
+ Q_UNUSED(deep);
+ isNull = true;
+ derData.clear();
+ keyLength = -1;
+}
+
+void QSslKeyPrivate::decodeDer(const QByteArray &der, bool deepClear)
+{
+ clear(deepClear);
+
+ if (der.isEmpty())
+ return;
+
+ QAsn1Element elem;
+ if (!elem.read(der) || elem.type() != QAsn1Element::SequenceType)
+ return;
+
+ if (type == QSsl::PublicKey) {
+ // key info
+ QDataStream keyStream(elem.value());
+ if (!elem.read(keyStream) || elem.type() != QAsn1Element::SequenceType)
+ return;
+ QVector<QAsn1Element> infoItems = elem.toVector();
+ if (infoItems.size() < 2 || infoItems[0].type() != QAsn1Element::ObjectIdentifierType)
+ return;
+ if (algorithm == QSsl::Rsa) {
+ if (infoItems[0].toObjectId() != RSA_ENCRYPTION_OID)
+ return;
+ // key data
+ if (!elem.read(keyStream) || elem.type() != QAsn1Element::BitStringType || elem.value().isEmpty())
+ return;
+ if (!elem.read(elem.value().mid(1)) || elem.type() != QAsn1Element::SequenceType)
+ return;
+ if (!elem.read(elem.value()) || elem.type() != QAsn1Element::IntegerType)
+ return;
+ keyLength = numberOfBits(elem.value());
+ } else if (algorithm == QSsl::Dsa) {
+ if (infoItems[0].toObjectId() != DSA_ENCRYPTION_OID)
+ return;
+ if (infoItems[1].type() != QAsn1Element::SequenceType)
+ return;
+ // key params
+ QVector<QAsn1Element> params = infoItems[1].toVector();
+ if (params.isEmpty() || params[0].type() != QAsn1Element::IntegerType)
+ return;
+ keyLength = numberOfBits(params[0].value());
+ }
+
+ } else {
+ QVector<QAsn1Element> items = elem.toVector();
+ if (items.isEmpty())
+ return;
+
+ // version
+ if (items[0].type() != QAsn1Element::IntegerType || items[0].value().toHex() != "00")
+ return;
+
+ if (algorithm == QSsl::Rsa) {
+ if (items.size() != 9 || items[1].type() != QAsn1Element::IntegerType)
+ return;
+ keyLength = numberOfBits(items[1].value());
+ } else if (algorithm == QSsl::Dsa) {
+ if (items.size() != 6 || items[1].type() != QAsn1Element::IntegerType)
+ return;
+ keyLength = numberOfBits(items[1].value());
+ }
+ }
+
+ derData = der;
+ isNull = false;
+}
+
+void QSslKeyPrivate::decodePem(const QByteArray &pem, const QByteArray &passPhrase,
+ bool deepClear)
+{
+ QMap<QByteArray, QByteArray> headers;
+ QByteArray data = derFromPem(pem, &headers);
+ if (headers.value("Proc-Type") == "4,ENCRYPTED") {
+ QList<QByteArray> dekInfo = headers.value("DEK-Info").split(',');
+ if (dekInfo.size() != 2) {
+ clear(deepClear);
+ return;
+ }
+
+ Cipher cipher;
+ if (dekInfo.first() == "DES-CBC") {
+ cipher = DesCbc;
+ } else if (dekInfo.first() == "DES-EDE3-CBC") {
+ cipher = DesEde3Cbc;
+ } else if (dekInfo.first() == "RC2-CBC") {
+ cipher = Rc2Cbc;
+ } else {
+ clear(deepClear);
+ return;
+ }
+
+ const QByteArray iv = QByteArray::fromHex(dekInfo.last());
+ const QByteArray key = deriveKey(cipher, passPhrase, iv);
+ data = decrypt(cipher, data, key, iv);
+ }
+ decodeDer(data, deepClear);
+}
+
+int QSslKeyPrivate::length() const
+{
+ return keyLength;
+}
+
+QByteArray QSslKeyPrivate::toPem(const QByteArray &passPhrase) const
+{
+ QByteArray data;
+ QMap<QByteArray, QByteArray> headers;
+
+ if (type == QSsl::PrivateKey && !passPhrase.isEmpty()) {
+ // ### use a cryptographically secure random number generator
+ QByteArray iv;
+ iv.resize(8);
+ for (int i = 0; i < iv.size(); ++i)
+ iv[i] = (qrand() & 0xff);
+
+ Cipher cipher = DesEde3Cbc;
+ const QByteArray key = deriveKey(cipher, passPhrase, iv);
+ data = encrypt(cipher, derData, key, iv);
+
+ headers.insert("Proc-Type", "4,ENCRYPTED");
+ headers.insert("DEK-Info", "DES-EDE3-CBC," + iv.toHex());
+ } else {
+ data = derData;
+ }
+
+ return pemFromDer(data, headers);
+}
+
+Qt::HANDLE QSslKeyPrivate::handle() const
+{
+ return opaque;
+}
diff --git a/src/network/ssl/qsslkey_winrt.cpp b/src/network/ssl/qsslkey_winrt.cpp
new file mode 100644
index 0000000000..c5b4146ee9
--- /dev/null
+++ b/src/network/ssl/qsslkey_winrt.cpp
@@ -0,0 +1,161 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsslkey.h"
+#include "qsslkey_p.h"
+#include "qsslcertificate_p.h"
+
+#include <QtCore/qfunctions_winrt.h>
+
+#include <wrl.h>
+#include <windows.security.cryptography.h>
+#include <windows.security.cryptography.core.h>
+#include <windows.security.cryptography.certificates.h>
+#include <windows.storage.streams.h>
+#include <robuffer.h>
+
+using namespace Microsoft::WRL;
+using namespace Microsoft::WRL::Wrappers;
+using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::Security::Cryptography;
+using namespace ABI::Windows::Security::Cryptography::Certificates;
+using namespace ABI::Windows::Security::Cryptography::Core;
+using namespace ABI::Windows::Storage::Streams;
+
+QT_USE_NAMESPACE
+
+struct SslKeyGlobal
+{
+ SslKeyGlobal()
+ {
+ HRESULT hr;
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Security_Cryptography_Core_CryptographicEngine).Get(),
+ &engine);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<ISymmetricKeyAlgorithmProviderStatics> keyProviderFactory;
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Security_Cryptography_Core_SymmetricKeyAlgorithmProvider).Get(),
+ &keyProviderFactory);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = keyProviderFactory->OpenAlgorithm(HString::MakeReference(L"DES_CBC").Get(),
+ &keyProviders[QSslKeyPrivate::DesCbc]);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = keyProviderFactory->OpenAlgorithm(HString::MakeReference(L"3DES_CBC").Get(),
+ &keyProviders[QSslKeyPrivate::DesEde3Cbc]);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = keyProviderFactory->OpenAlgorithm(HString::MakeReference(L"RC2_CBC").Get(),
+ &keyProviders[QSslKeyPrivate::Rc2Cbc]);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Security_Cryptography_CryptographicBuffer).Get(),
+ &bufferFactory);
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+
+ ComPtr<ICryptographicEngineStatics> engine;
+ QHash<QSslKeyPrivate::Cipher, ComPtr<ISymmetricKeyAlgorithmProvider>> keyProviders;
+ ComPtr<ICryptographicBufferStatics> bufferFactory;
+};
+Q_GLOBAL_STATIC(SslKeyGlobal, g)
+
+static QByteArray doCrypt(QSslKeyPrivate::Cipher cipher, QByteArray data, const QByteArray &key, const QByteArray &iv, bool encrypt)
+{
+ HRESULT hr;
+
+ ISymmetricKeyAlgorithmProvider *keyProvider = g->keyProviders[cipher].Get();
+ Q_ASSERT(keyProvider);
+
+ ComPtr<IBuffer> keyBuffer;
+ hr = g->bufferFactory->CreateFromByteArray(key.length(), (BYTE *)key.data(), &keyBuffer);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<ICryptographicKey> cryptographicKey;
+ hr = keyProvider->CreateSymmetricKey(keyBuffer.Get(), &cryptographicKey);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ UINT32 blockLength;
+ hr = keyProvider->get_BlockLength(&blockLength);
+ Q_ASSERT_SUCCEEDED(hr);
+ if (encrypt) { // Add padding
+ const char padding = blockLength - data.length() % blockLength;
+ data += QByteArray(padding, padding);
+ }
+
+ ComPtr<IBuffer> dataBuffer;
+ hr = g->bufferFactory->CreateFromByteArray(data.length(), (BYTE *)data.data(), &dataBuffer);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IBuffer> ivBuffer;
+ hr = g->bufferFactory->CreateFromByteArray(iv.length(), (BYTE *)iv.data(), &ivBuffer);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IBuffer> resultBuffer;
+ hr = encrypt ? g->engine->Encrypt(cryptographicKey.Get(), dataBuffer.Get(), ivBuffer.Get(), &resultBuffer)
+ : g->engine->Decrypt(cryptographicKey.Get(), dataBuffer.Get(), ivBuffer.Get(), &resultBuffer);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ UINT32 resultLength;
+ hr = resultBuffer->get_Length(&resultLength);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<Windows::Storage::Streams::IBufferByteAccess> bufferAccess;
+ hr = resultBuffer.As(&bufferAccess);
+ Q_ASSERT_SUCCEEDED(hr);
+ byte *resultData;
+ hr = bufferAccess->Buffer(&resultData);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ if (!encrypt) { // Remove padding
+ const uchar padding = resultData[resultLength - 1];
+ if (padding > 0 && padding <= blockLength)
+ resultLength -= padding;
+ else
+ qWarning("Invalid padding length of %u; decryption likely failed.", padding);
+ }
+
+ return QByteArray(reinterpret_cast<const char *>(resultData), resultLength);
+}
+
+QByteArray QSslKeyPrivate::decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv)
+{
+ return doCrypt(cipher, data, key, iv, false);
+}
+
+QByteArray QSslKeyPrivate::encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key, const QByteArray &iv)
+{
+ return doCrypt(cipher, data, key, iv, true);
+}
diff --git a/src/network/ssl/qsslsocket.cpp b/src/network/ssl/qsslsocket.cpp
index 90f6e25b97..b092e5e980 100644
--- a/src/network/ssl/qsslsocket.cpp
+++ b/src/network/ssl/qsslsocket.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
** Contact: http://www.qt-project.org/legal
**
@@ -291,7 +291,12 @@
#include "qsslsocket.h"
#include "qsslcipher.h"
+#ifndef QT_NO_OPENSSL
#include "qsslsocket_openssl_p.h"
+#endif
+#ifdef Q_OS_WINRT
+#include "qsslsocket_winrt_p.h"
+#endif
#include "qsslconfiguration_p.h"
#include <QtCore/qdebug.h>
@@ -880,6 +885,7 @@ QSslConfiguration QSslSocket::sslConfiguration() const
QSslConfigurationPrivate *copy = new QSslConfigurationPrivate(d->configuration);
copy->ref.store(0); // the QSslConfiguration constructor refs up
copy->sessionCipher = d->sessionCipher();
+ copy->sessionProtocol = d->sessionProtocol();
return QSslConfiguration(copy);
}
@@ -1075,6 +1081,20 @@ QSslCipher QSslSocket::sessionCipher() const
}
/*!
+ Returns the socket's SSL/TLS protocol or UnknownProtocol if the
+ connection isn't encrypted. The socket's protocol for the session
+ is set during the handshake phase.
+
+ \sa protocol(), setProtocol()
+*/
+QSsl::SslProtocol QSslSocket::sessionProtocol() const
+{
+ Q_D(const QSslSocket);
+ return d->sessionProtocol();
+}
+
+
+/*!
Sets the socket's private \l {QSslKey} {key} to \a key. The
private key and the local \l {QSslCertificate} {certificate} are
used by clients and servers that must prove their identity to
@@ -1667,6 +1687,32 @@ QString QSslSocket::sslLibraryVersionString()
}
/*!
+ \since 5.4
+ Returns the version number of the SSL library in use at compile
+ time. If no SSL support is available then this will return an
+ undefined value.
+
+ \sa sslLibraryVersionNumber()
+*/
+long QSslSocket::sslLibraryBuildVersionNumber()
+{
+ return QSslSocketPrivate::sslLibraryBuildVersionNumber();
+}
+
+/*!
+ \since 5.4
+ Returns the version string of the SSL library in use at compile
+ time. If no SSL support is available then this will return an
+ empty value.
+
+ \sa sslLibraryVersionString()
+*/
+QString QSslSocket::sslLibraryBuildVersionString()
+{
+ return QSslSocketPrivate::sslLibraryBuildVersionString();
+}
+
+/*!
Starts a delayed SSL handshake for a client connection. This
function can be called when the socket is in the \l ConnectedState
but still in the \l UnencryptedMode. If it is not yet connected,
@@ -1848,8 +1894,10 @@ void QSslSocket::disconnectFromHost()
emit stateChanged(d->state);
}
- if (!d->writeBuffer.isEmpty())
+ if (!d->writeBuffer.isEmpty()) {
+ d->pendingClose = true;
return;
+ }
if (d->mode == UnencryptedMode) {
d->plainSocket->disconnectFromHost();
@@ -2098,6 +2146,7 @@ void QSslConfigurationPrivate::deepCopyDefaultConfiguration(QSslConfigurationPri
ptr->localCertificateChain = global->localCertificateChain;
ptr->privateKey = global->privateKey;
ptr->sessionCipher = global->sessionCipher;
+ ptr->sessionProtocol = global->sessionProtocol;
ptr->ciphers = global->ciphers;
ptr->caCertificates = global->caCertificates;
ptr->protocol = global->protocol;
@@ -2466,6 +2515,65 @@ QSharedPointer<QSslContext> QSslSocketPrivate::sslContext(QSslSocket *socket)
return (socket) ? socket->d_func()->sslContextPointer : QSharedPointer<QSslContext>();
}
+bool QSslSocketPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
+{
+ QStringList commonNameList = cert.subjectInfo(QSslCertificate::CommonName);
+
+ foreach (const QString &commonName, commonNameList) {
+ if (isMatchingHostname(commonName.toLower(), peerName.toLower())) {
+ return true;
+ }
+ }
+
+ foreach (const QString &altName, cert.subjectAlternativeNames().values(QSsl::DnsEntry)) {
+ if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool QSslSocketPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
+{
+ int wildcard = cn.indexOf(QLatin1Char('*'));
+
+ // Check this is a wildcard cert, if not then just compare the strings
+ if (wildcard < 0)
+ return cn == hostname;
+
+ int firstCnDot = cn.indexOf(QLatin1Char('.'));
+ int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
+
+ // Check at least 3 components
+ if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
+ return false;
+
+ // Check * is last character of 1st component (ie. there's a following .)
+ if (wildcard+1 != firstCnDot)
+ return false;
+
+ // Check only one star
+ if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
+ return false;
+
+ // Check characters preceding * (if any) match
+ if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
+ return false;
+
+ // Check characters following first . match
+ if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
+ return false;
+
+ // Check if the hostname is an IP address, if so then wildcards are not allowed
+ QHostAddress addr(hostname);
+ if (!addr.isNull())
+ return false;
+
+ // Ok, I guess this was a wildcard CN and the hostname matches.
+ return true;
+}
+
QT_END_NAMESPACE
#include "moc_qsslsocket.cpp"
diff --git a/src/network/ssl/qsslsocket.h b/src/network/ssl/qsslsocket.h
index d89933efda..312ddb9850 100644
--- a/src/network/ssl/qsslsocket.h
+++ b/src/network/ssl/qsslsocket.h
@@ -140,6 +140,7 @@ public:
QSslCertificate peerCertificate() const;
QList<QSslCertificate> peerCertificateChain() const;
QSslCipher sessionCipher() const;
+ QSsl::SslProtocol sessionProtocol() const;
// Private keys, for server sockets.
void setPrivateKey(const QSslKey &key);
@@ -182,6 +183,8 @@ public:
static bool supportsSsl();
static long sslLibraryVersionNumber();
static QString sslLibraryVersionString();
+ static long sslLibraryBuildVersionNumber();
+ static QString sslLibraryBuildVersionString();
void ignoreSslErrors(const QList<QSslError> &errors);
@@ -214,7 +217,7 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_flushWriteBuffer())
Q_PRIVATE_SLOT(d_func(), void _q_flushReadBuffer())
Q_PRIVATE_SLOT(d_func(), void _q_resumeImplementation())
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
Q_PRIVATE_SLOT(d_func(), void _q_caRootLoaded(QSslCertificate,QSslCertificate))
#endif
friend class QSslSocketBackendPrivate;
diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp
index 0315749cb3..dc08954d6e 100644
--- a/src/network/ssl/qsslsocket_openssl.cpp
+++ b/src/network/ssl/qsslsocket_openssl.cpp
@@ -62,6 +62,7 @@
#include "qsslsocket.h"
#include "qsslcertificate_p.h"
#include "qsslcipher_p.h"
+#include "qsslkey_p.h"
#include <QtCore/qdatetime.h>
#include <QtCore/qdebug.h>
@@ -585,6 +586,16 @@ QString QSslSocketPrivate::sslLibraryVersionString()
return QString::fromLatin1(versionString);
}
+long QSslSocketPrivate::sslLibraryBuildVersionNumber()
+{
+ return OPENSSL_VERSION_NUMBER;
+}
+
+QString QSslSocketPrivate::sslLibraryBuildVersionString()
+{
+ return QLatin1String(OPENSSL_VERSION_TEXT);
+}
+
/*!
\internal
@@ -1429,6 +1440,28 @@ QSslCipher QSslSocketBackendPrivate::sessionCipher() const
return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
}
+QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
+{
+ if (!ssl)
+ return QSsl::UnknownProtocol;
+ int ver = q_SSL_version(ssl);
+
+ switch (ver) {
+ case 0x2:
+ return QSsl::SslV2;
+ case 0x300:
+ return QSsl::SslV3;
+ case 0x301:
+ return QSsl::TlsV1_0;
+ case 0x302:
+ return QSsl::TlsV1_1;
+ case 0x303:
+ return QSsl::TlsV1_2;
+ }
+
+ return QSsl::UnknownProtocol;
+}
+
void QSslSocketBackendPrivate::continueHandshake()
{
Q_Q(QSslSocket);
@@ -1519,65 +1552,6 @@ QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates
return certificates;
}
-bool QSslSocketBackendPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
-{
- QStringList commonNameList = cert.subjectInfo(QSslCertificate::CommonName);
-
- foreach (const QString &commonName, commonNameList) {
- if (isMatchingHostname(commonName.toLower(), peerName.toLower())) {
- return true;
- }
- }
-
- foreach (const QString &altName, cert.subjectAlternativeNames().values(QSsl::DnsEntry)) {
- if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
- return true;
- }
- }
-
- return false;
-}
-
-bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
-{
- int wildcard = cn.indexOf(QLatin1Char('*'));
-
- // Check this is a wildcard cert, if not then just compare the strings
- if (wildcard < 0)
- return cn == hostname;
-
- int firstCnDot = cn.indexOf(QLatin1Char('.'));
- int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
-
- // Check at least 3 components
- if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
- return false;
-
- // Check * is last character of 1st component (ie. there's a following .)
- if (wildcard+1 != firstCnDot)
- return false;
-
- // Check only one star
- if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
- return false;
-
- // Check characters preceding * (if any) match
- if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
- return false;
-
- // Check characters following first . match
- if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
- return false;
-
- // Check if the hostname is an IP address, if so then wildcards are not allowed
- QHostAddress addr(hostname);
- if (!addr.isNull())
- return false;
-
- // Ok, I guess this was a wildcard CN and the hostname matches.
- return true;
-}
-
QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certificateChain, const QString &hostName)
{
QList<QSslError> errors;
@@ -1703,4 +1677,72 @@ QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certifi
return errors;
}
+bool QSslSocketBackendPrivate::importPKCS12(QIODevice *device,
+ QSslKey *key, QSslCertificate *cert,
+ QList<QSslCertificate> *caCertificates,
+ const QByteArray &passPhrase)
+{
+ if (!supportsSsl())
+ return false;
+
+ // These are required
+ Q_ASSERT(device);
+ Q_ASSERT(key);
+ Q_ASSERT(cert);
+
+ // Read the file into a BIO
+ QByteArray pkcs12data = device->readAll();
+ if (pkcs12data.size() == 0)
+ return false;
+
+ BIO *bio = q_BIO_new_mem_buf(const_cast<char *>(pkcs12data.constData()), pkcs12data.size());
+
+ // Create the PKCS#12 object
+ PKCS12 *p12 = q_d2i_PKCS12_bio(bio, 0);
+ if (!p12) {
+ qWarning("Unable to read PKCS#12 structure, %s", q_ERR_error_string(q_ERR_get_error(), 0));
+ q_BIO_free(bio);
+ return false;
+ }
+
+ // Extract the data
+ EVP_PKEY *pkey;
+ X509 *x509;
+ STACK_OF(X509) *ca = 0;
+
+ if (!q_PKCS12_parse(p12, passPhrase.constData(), &pkey, &x509, &ca)) {
+ qWarning("Unable to parse PKCS#12 structure, %s", q_ERR_error_string(q_ERR_get_error(), 0));
+ q_PKCS12_free(p12);
+ q_BIO_free(bio);
+ return false;
+ }
+
+ // Convert to Qt types
+ if (!key->d->fromEVP_PKEY(pkey)) {
+ qWarning("Unable to convert private key");
+ q_sk_pop_free(reinterpret_cast<STACK *>(ca), reinterpret_cast<void(*)(void*)>(q_sk_free));
+ q_X509_free(x509);
+ q_EVP_PKEY_free(pkey);
+ q_PKCS12_free(p12);
+ q_BIO_free(bio);
+
+ return false;
+ }
+
+ *cert = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
+
+ if (caCertificates)
+ *caCertificates = QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(ca);
+
+ // Clean up
+ q_sk_pop_free(reinterpret_cast<STACK *>(ca), reinterpret_cast<void(*)(void*)>(q_sk_free));
+ q_X509_free(x509);
+ q_EVP_PKEY_free(pkey);
+ q_PKCS12_free(p12);
+ q_BIO_free(bio);
+
+ return true;
+}
+
+
QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslsocket_openssl_p.h b/src/network/ssl/qsslsocket_openssl_p.h
index c8b23e6cad..3a1df7c420 100644
--- a/src/network/ssl/qsslsocket_openssl_p.h
+++ b/src/network/ssl/qsslsocket_openssl_p.h
@@ -131,6 +131,7 @@ public:
void disconnectFromHost();
void disconnected();
QSslCipher sessionCipher() const;
+ QSsl::SslProtocol sessionProtocol() const;
void continueHandshake();
bool checkSslErrors();
#ifdef Q_OS_WIN
@@ -141,10 +142,12 @@ public:
Q_AUTOTEST_EXPORT static long setupOpenSslOptions(QSsl::SslProtocol protocol, QSsl::SslOptions sslOptions);
static QSslCipher QSslCipher_from_SSL_CIPHER(SSL_CIPHER *cipher);
static QList<QSslCertificate> STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509);
- static bool isMatchingHostname(const QSslCertificate &cert, const QString &peerName);
- Q_AUTOTEST_EXPORT static bool isMatchingHostname(const QString &cn, const QString &hostname);
static QList<QSslError> verify(QList<QSslCertificate> certificateChain, const QString &hostName);
static QString getErrorsFromOpenSsl();
+ static bool importPKCS12(QIODevice *device,
+ QSslKey *key, QSslCertificate *cert,
+ QList<QSslCertificate> *caCertificates,
+ const QByteArray &passPhrase);
};
#ifdef Q_OS_WIN
diff --git a/src/network/ssl/qsslsocket_openssl_symbols.cpp b/src/network/ssl/qsslsocket_openssl_symbols.cpp
index 4e6200f880..6f22ab726f 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols.cpp
+++ b/src/network/ssl/qsslsocket_openssl_symbols.cpp
@@ -146,6 +146,7 @@ DEFINEFUNC(int, CRYPTO_num_locks, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(void, CRYPTO_set_locking_callback, void (*a)(int, int, const char *, int), a, return, DUMMYARG)
DEFINEFUNC(void, CRYPTO_set_id_callback, unsigned long (*a)(), a, return, DUMMYARG)
DEFINEFUNC(void, CRYPTO_free, void *a, a, return, DUMMYARG)
+DEFINEFUNC(DSA *, DSA_new, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(void, DSA_free, DSA *a, a, return, DUMMYARG)
#if OPENSSL_VERSION_NUMBER < 0x00908000L
DEFINEFUNC3(X509 *, d2i_X509, X509 **a, a, unsigned char **b, b, long c, c, return 0, return)
@@ -186,6 +187,7 @@ DEFINEFUNC2(int, PEM_write_bio_DSA_PUBKEY, BIO *a, a, DSA *b, b, return 0, retur
DEFINEFUNC2(int, PEM_write_bio_RSA_PUBKEY, BIO *a, a, RSA *b, b, return 0, return)
DEFINEFUNC2(void, RAND_seed, const void *a, a, int b, b, return, DUMMYARG)
DEFINEFUNC(int, RAND_status, void, DUMMYARG, return -1, return)
+DEFINEFUNC(RSA *, RSA_new, DUMMYARG, DUMMYARG, return 0, return)
DEFINEFUNC(void, RSA_free, RSA *a, a, return, DUMMYARG)
DEFINEFUNC(int, sk_num, STACK *a, a, return -1, return)
DEFINEFUNC2(void, sk_pop_free, STACK *a, a, void (*b)(void*), b, return, DUMMYARG)
@@ -239,6 +241,7 @@ DEFINEFUNC(const SSL_CIPHER *, SSL_get_current_cipher, SSL *a, a, return 0, retu
#else
DEFINEFUNC(SSL_CIPHER *, SSL_get_current_cipher, SSL *a, a, return 0, return)
#endif
+DEFINEFUNC(int, SSL_version, const SSL *a, a, return 0, return)
DEFINEFUNC2(int, SSL_get_error, SSL *a, a, int b, b, return -1, return)
DEFINEFUNC(STACK_OF(X509) *, SSL_get_peer_cert_chain, SSL *a, a, return 0, return)
DEFINEFUNC(X509 *, SSL_get_peer_certificate, SSL *a, a, return 0, return)
@@ -316,6 +319,7 @@ DEFINEFUNC2(int, ASN1_STRING_print, BIO *a, a, const ASN1_STRING *b, b, return 0
#else
DEFINEFUNC2(int, ASN1_STRING_print, BIO *a, a, ASN1_STRING *b, b, return 0, return)
#endif
+DEFINEFUNC2(int, X509_check_issued, X509 *a, a, X509 *b, b, return -1, return)
DEFINEFUNC(X509_NAME *, X509_get_issuer_name, X509 *a, a, return 0, return)
DEFINEFUNC(X509_NAME *, X509_get_subject_name, X509 *a, a, return 0, return)
DEFINEFUNC(int, X509_verify_cert, X509_STORE_CTX *a, a, return -1, return)
@@ -370,6 +374,11 @@ DEFINEFUNC(EC_KEY *, EC_KEY_new_by_curve_name, int nid, nid, return 0, return)
DEFINEFUNC(void, EC_KEY_free, EC_KEY *ecdh, ecdh, return, DUMMYARG)
#endif // OPENSSL_NO_EC
+DEFINEFUNC5(int, PKCS12_parse, PKCS12 *p12, p12, const char *pass, pass, EVP_PKEY **pkey, pkey, \
+ X509 **cert, cert, STACK_OF(X509) **ca, ca, return 1, return);
+DEFINEFUNC2(PKCS12 *, d2i_PKCS12_bio, BIO *bio, bio, PKCS12 **pkcs12, pkcs12, return 0, return);
+DEFINEFUNC(void, PKCS12_free, PKCS12 *pkcs12, pkcs12, return, DUMMYARG)
+
#define RESOLVEFUNC(func) \
if (!(_q_##func = _q_PTR_##func(libs.first->resolve(#func))) \
&& !(_q_##func = _q_PTR_##func(libs.second->resolve(#func)))) \
@@ -688,6 +697,7 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(CRYPTO_num_locks)
RESOLVEFUNC(CRYPTO_set_id_callback)
RESOLVEFUNC(CRYPTO_set_locking_callback)
+ RESOLVEFUNC(DSA_new)
RESOLVEFUNC(DSA_free)
RESOLVEFUNC(ERR_error_string)
RESOLVEFUNC(ERR_get_error)
@@ -720,6 +730,7 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(PEM_write_bio_RSA_PUBKEY)
RESOLVEFUNC(RAND_seed)
RESOLVEFUNC(RAND_status)
+ RESOLVEFUNC(RSA_new)
RESOLVEFUNC(RSA_free)
RESOLVEFUNC(sk_new_null)
RESOLVEFUNC(sk_push)
@@ -748,6 +759,7 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(SSL_free)
RESOLVEFUNC(SSL_get_ciphers)
RESOLVEFUNC(SSL_get_current_cipher)
+ RESOLVEFUNC(SSL_version)
RESOLVEFUNC(SSL_get_error)
RESOLVEFUNC(SSL_get_peer_cert_chain)
RESOLVEFUNC(SSL_get_peer_certificate)
@@ -821,6 +833,7 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(BASIC_CONSTRAINTS_free)
RESOLVEFUNC(AUTHORITY_KEYID_free)
RESOLVEFUNC(ASN1_STRING_print)
+ RESOLVEFUNC(X509_check_issued)
RESOLVEFUNC(X509_get_issuer_name)
RESOLVEFUNC(X509_get_subject_name)
RESOLVEFUNC(X509_verify_cert)
@@ -851,6 +864,9 @@ bool q_resolveOpenSslSymbols()
RESOLVEFUNC(EC_KEY_new_by_curve_name)
RESOLVEFUNC(EC_KEY_free)
#endif // OPENSSL_NO_EC
+ RESOLVEFUNC(PKCS12_parse)
+ RESOLVEFUNC(d2i_PKCS12_bio)
+ RESOLVEFUNC(PKCS12_free)
symbolsResolved = true;
delete libs.first;
diff --git a/src/network/ssl/qsslsocket_openssl_symbols_p.h b/src/network/ssl/qsslsocket_openssl_symbols_p.h
index 68f5709b93..66f45f4706 100644
--- a/src/network/ssl/qsslsocket_openssl_symbols_p.h
+++ b/src/network/ssl/qsslsocket_openssl_symbols_p.h
@@ -233,6 +233,7 @@ int q_CRYPTO_num_locks();
void q_CRYPTO_set_locking_callback(void (*a)(int, int, const char *, int));
void q_CRYPTO_set_id_callback(unsigned long (*a)());
void q_CRYPTO_free(void *a);
+DSA *q_DSA_new();
void q_DSA_free(DSA *a);
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
// 0.9.8 broke SC and BC by changing this function's signature.
@@ -277,6 +278,7 @@ int q_PEM_write_bio_DSA_PUBKEY(BIO *a, DSA *b);
int q_PEM_write_bio_RSA_PUBKEY(BIO *a, RSA *b);
void q_RAND_seed(const void *a, int b);
int q_RAND_status();
+RSA *q_RSA_new();
void q_RSA_free(RSA *a);
int q_sk_num(STACK *a);
void q_sk_pop_free(STACK *a, void (*b)(void *));
@@ -330,6 +332,7 @@ const SSL_CIPHER *q_SSL_get_current_cipher(SSL *a);
#else
SSL_CIPHER *q_SSL_get_current_cipher(SSL *a);
#endif
+int q_SSL_version(const SSL *a);
int q_SSL_get_error(SSL *a, int b);
STACK_OF(X509) *q_SSL_get_peer_cert_chain(SSL *a);
X509 *q_SSL_get_peer_certificate(SSL *a);
@@ -407,6 +410,7 @@ int q_ASN1_STRING_print(BIO *a, const ASN1_STRING *b);
#else
int q_ASN1_STRING_print(BIO *a, ASN1_STRING *b);
#endif
+int q_X509_check_issued(X509 *a, X509 *b);
X509_NAME *q_X509_get_issuer_name(X509 *a);
X509_NAME *q_X509_get_subject_name(X509 *a);
int q_X509_verify_cert(X509_STORE_CTX *ctx);
@@ -441,6 +445,12 @@ void q_EC_KEY_free(EC_KEY *ecdh);
#define q_SSL_CTX_set_tmp_ecdh(ctx, ecdh) q_SSL_CTX_ctrl((ctx), SSL_CTRL_SET_TMP_ECDH, 0, (char *)ecdh)
#endif // OPENSSL_NO_EC
+// PKCS#12 support
+int q_PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca);
+PKCS12 *q_d2i_PKCS12_bio(BIO *bio, PKCS12 **pkcs12);
+void q_PKCS12_free(PKCS12 *pkcs12);
+
+
#define q_BIO_get_mem_data(b, pp) (int)q_BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)pp)
#define q_BIO_pending(b) (int)q_BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL)
#ifdef SSLEAY_MACROS
diff --git a/src/network/ssl/qsslsocket_p.h b/src/network/ssl/qsslsocket_p.h
index 6281753225..bda36d2649 100644
--- a/src/network/ssl/qsslsocket_p.h
+++ b/src/network/ssl/qsslsocket_p.h
@@ -59,7 +59,9 @@
#include <private/qtcpsocket_p.h>
#include "qsslkey.h"
#include "qsslconfiguration_p.h"
-#include <private/qsslcontext_p.h>
+#ifndef QT_NO_OPENSSL
+#include <private/qsslcontext_openssl_p.h>
+#endif
#include <QtCore/qstringlist.h>
@@ -70,11 +72,13 @@
#include <CoreFoundation/CFArray.h>
#elif defined(Q_OS_WIN)
#include <QtCore/qt_windows.h>
+#ifndef Q_OS_WINRT
#include <wincrypt.h>
+#endif // !Q_OS_WINRT
#ifndef HCRYPTPROV_LEGACY
#define HCRYPTPROV_LEGACY HCRYPTPROV
-#endif
-#endif
+#endif // !HCRYPTPROV_LEGACY
+#endif // Q_OS_WIN
QT_BEGIN_NAMESPACE
@@ -84,7 +88,7 @@ QT_BEGIN_NAMESPACE
typedef OSStatus (*PtrSecTrustCopyAnchorCertificates)(CFArrayRef*);
#endif
-#if defined(Q_OS_WIN)
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
#if defined(Q_OS_WINCE)
typedef HCERTSTORE (WINAPI *PtrCertOpenSystemStoreW)(LPCSTR, DWORD, HCRYPTPROV_LEGACY, DWORD, const void*);
#else
@@ -92,7 +96,7 @@ QT_BEGIN_NAMESPACE
#endif
typedef PCCERT_CONTEXT (WINAPI *PtrCertFindCertificateInStore)(HCERTSTORE, DWORD, DWORD, DWORD, const void*, PCCERT_CONTEXT);
typedef BOOL (WINAPI *PtrCertCloseStore)(HCERTSTORE, DWORD);
-#endif
+#endif // Q_OS_WIN && !Q_OS_WINRT
@@ -129,6 +133,8 @@ public:
static bool supportsSsl();
static long sslLibraryVersionNumber();
static QString sslLibraryVersionString();
+ static long sslLibraryBuildVersionNumber();
+ static QString sslLibraryBuildVersionString();
static void ensureInitialized();
static void deinitialize();
static QList<QSslCipher> defaultCiphers();
@@ -144,16 +150,18 @@ public:
QRegExp::PatternSyntax syntax);
static void addDefaultCaCertificate(const QSslCertificate &cert);
static void addDefaultCaCertificates(const QList<QSslCertificate> &certs);
+ static bool isMatchingHostname(const QSslCertificate &cert, const QString &peerName);
+ Q_AUTOTEST_EXPORT static bool isMatchingHostname(const QString &cn, const QString &hostname);
#if defined(Q_OS_MACX)
static PtrSecCertificateCopyData ptrSecCertificateCopyData;
static PtrSecTrustSettingsCopyCertificates ptrSecTrustSettingsCopyCertificates;
static PtrSecTrustCopyAnchorCertificates ptrSecTrustCopyAnchorCertificates;
-#elif defined(Q_OS_WIN)
+#elif defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
static PtrCertOpenSystemStoreW ptrCertOpenSystemStoreW;
static PtrCertFindCertificateInStore ptrCertFindCertificateInStore;
static PtrCertCloseStore ptrCertCloseStore;
-#endif
+#endif // Q_OS_WIN && !Q_OS_WINRT
// The socket itself, including private slots.
QTcpSocket *plainSocket;
@@ -174,7 +182,7 @@ public:
void _q_flushWriteBuffer();
void _q_flushReadBuffer();
void _q_resumeImplementation();
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
virtual void _q_caRootLoaded(QSslCertificate,QSslCertificate) = 0;
#endif
@@ -190,6 +198,7 @@ public:
virtual void disconnectFromHost() = 0;
virtual void disconnected() = 0;
virtual QSslCipher sessionCipher() const = 0;
+ virtual QSsl::SslProtocol sessionProtocol() const = 0;
virtual void continueHandshake() = 0;
Q_AUTOTEST_EXPORT static bool rootCertOnDemandLoadingSupported();
diff --git a/src/network/ssl/qsslsocket_winrt.cpp b/src/network/ssl/qsslsocket_winrt.cpp
new file mode 100644
index 0000000000..c9ddd9ec1b
--- /dev/null
+++ b/src/network/ssl/qsslsocket_winrt.cpp
@@ -0,0 +1,688 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qsslsocket_winrt_p.h"
+#include "qsslsocket.h"
+#include "qsslcertificate_p.h"
+#include "qsslcipher_p.h"
+
+#include <QtCore/QCoreApplication>
+#include <QtCore/QSysInfo>
+#include <QtCore/qfunctions_winrt.h>
+#include <private/qnativesocketengine_winrt_p.h>
+
+#include <windows.networking.h>
+#include <windows.networking.sockets.h>
+#include <windows.security.cryptography.certificates.h>
+#include <robuffer.h>
+
+using namespace Microsoft::WRL;
+using namespace Microsoft::WRL::Wrappers;
+using namespace ABI::Windows::Foundation;
+using namespace ABI::Windows::Foundation::Collections;
+using namespace ABI::Windows::Networking;
+using namespace ABI::Windows::Networking::Sockets;
+using namespace ABI::Windows::Security::Cryptography::Certificates;
+using namespace ABI::Windows::Storage::Streams;
+
+QT_BEGIN_NAMESPACE
+
+// For QSet<QSslError>
+inline uint qHash(const QSslError &error, uint seed)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(error)))
+{ return (qHash(error.error()) ^ seed); }
+
+// For QSet<QSslCertificate>
+inline uint qHash(const QSslCertificate &certificate, uint seed)
+ Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(certificate)))
+{ return (qHash(certificate.handle()) ^ seed); }
+
+bool QSslSocketPrivate::s_libraryLoaded = true;
+bool QSslSocketPrivate::s_loadRootCertsOnDemand = true;
+bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
+
+struct SslSocketGlobal
+{
+ SslSocketGlobal()
+ {
+ HRESULT hr;
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
+ &hostNameFactory);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<ICertificateStoresStatics> certificateStores;
+ hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Security_Cryptography_Certificates_CertificateStores).Get(),
+ &certificateStores);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ hr = certificateStores->get_TrustedRootCertificationAuthorities(&rootStore);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<IAsyncOperation<IVectorView<Certificate *> *>> op;
+ hr = certificateStores->FindAllAsync(&op);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IVectorView<Certificate *>> certificates;
+ hr = QWinRTFunctions::await(op, certificates.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
+ quint32 size;
+ hr = certificates->get_Size(&size);
+ Q_ASSERT_SUCCEEDED(hr);
+ for (quint32 i = 0; i < size; ++i) {
+ ComPtr<ICertificate> certificate;
+ hr = certificates->GetAt(i, &certificate);
+ Q_ASSERT_SUCCEEDED(hr);
+ systemCaCertificates.append(QSslCertificatePrivate::QSslCertificate_from_Certificate(certificate.Get()));
+ }
+ }
+
+ void syncCaCertificates(const QSet<QSslCertificate> &add, const QSet<QSslCertificate> &remove)
+ {
+ QMutexLocker locker(&certificateMutex);
+ foreach (const QSslCertificate &certificate, add) {
+ QHash<QSslCertificate, QAtomicInt>::iterator it = additionalCertificates.find(certificate);
+ if (it != additionalCertificates.end()) {
+ it.value().ref(); // Add a reference
+ } else {
+ // install certificate
+ HRESULT hr;
+ hr = rootStore->Add(static_cast<ICertificate *>(certificate.handle()));
+ Q_ASSERT_SUCCEEDED(hr);
+ additionalCertificates.insert(certificate, 1);
+ }
+ }
+ foreach (const QSslCertificate &certificate, remove) {
+ QHash<QSslCertificate, QAtomicInt>::iterator it = additionalCertificates.find(certificate);
+ if (it != additionalCertificates.end() && !it.value().deref()) {
+ // no more references, remove certificate
+ HRESULT hr;
+ hr = rootStore->Delete(static_cast<ICertificate *>(certificate.handle()));
+ Q_ASSERT_SUCCEEDED(hr);
+ additionalCertificates.erase(it);
+ }
+ }
+ }
+
+ ComPtr<IHostNameFactory> hostNameFactory;
+ QList<QSslCertificate> systemCaCertificates;
+
+private:
+ QMutex certificateMutex;
+ ComPtr<ICertificateStore> rootStore;
+ QHash<QSslCertificate, QAtomicInt> additionalCertificates;
+};
+Q_GLOBAL_STATIC(SslSocketGlobal, g)
+
+// Called on the socket's thread to avoid cross-thread deletion
+void QSslSocketConnectionHelper::disconnectSocketFromHost()
+{
+ if (d->plainSocket)
+ d->plainSocket->disconnectFromHost();
+}
+
+QSslSocketBackendPrivate::QSslSocketBackendPrivate()
+ : connectionHelper(new QSslSocketConnectionHelper(this))
+{
+}
+
+QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
+{
+ g->syncCaCertificates(QSet<QSslCertificate>(), previousCaCertificates);
+}
+
+void QSslSocketPrivate::deinitialize()
+{
+ Q_UNIMPLEMENTED();
+}
+
+bool QSslSocketPrivate::supportsSsl()
+{
+ return true;
+}
+
+void QSslSocketPrivate::ensureInitialized()
+{
+ if (s_loadedCiphersAndCerts)
+ return;
+ s_loadedCiphersAndCerts = true;
+ resetDefaultCiphers();
+}
+
+long QSslSocketPrivate::sslLibraryVersionNumber()
+{
+ return QSysInfo::windowsVersion();
+}
+
+QString QSslSocketPrivate::sslLibraryVersionString()
+{
+ switch (QSysInfo::windowsVersion()) {
+ case QSysInfo::WV_WINDOWS8_1:
+ return QStringLiteral("Windows Runtime 8.1 SSL library");
+ default:
+ break;
+ }
+ return QStringLiteral("Windows Runtime SSL library");
+}
+
+long QSslSocketPrivate::sslLibraryBuildVersionNumber()
+{
+ Q_UNIMPLEMENTED();
+ return 0;
+}
+
+QString QSslSocketPrivate::sslLibraryBuildVersionString()
+{
+ Q_UNIMPLEMENTED();
+ return QString::number(sslLibraryBuildVersionNumber());
+}
+
+void QSslSocketPrivate::resetDefaultCiphers()
+{
+ setDefaultSupportedCiphers(QSslSocketBackendPrivate::defaultCiphers());
+ setDefaultCiphers(QSslSocketBackendPrivate::defaultCiphers());
+}
+
+
+QList<QSslCipher> QSslSocketBackendPrivate::defaultCiphers()
+{
+ QList<QSslCipher> ciphers;
+ const QString protocolStrings[] = { QStringLiteral("SSLv3"), QStringLiteral("TLSv1"),
+ QStringLiteral("TLSv1.1"), QStringLiteral("TLSv1.2") };
+ const QSsl::SslProtocol protocols[] = { QSsl::SslV3, QSsl::TlsV1_0, QSsl::TlsV1_1, QSsl::TlsV1_2 };
+ for (int i = 0; i < ARRAYSIZE(protocols); ++i) {
+ QSslCipher cipher;
+ cipher.d->isNull = false;
+ cipher.d->name = QStringLiteral("WINRT");
+ cipher.d->protocol = protocols[i];
+ cipher.d->protocolString = protocolStrings[i];
+ ciphers.append(cipher);
+ }
+ return ciphers;
+}
+
+QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
+{
+ return g->systemCaCertificates;
+}
+
+void QSslSocketBackendPrivate::startClientEncryption()
+{
+ Q_Q(QSslSocket);
+
+ QSsl::SslProtocol protocol = q->protocol();
+ switch (q->protocol()) {
+ case QSsl::AnyProtocol:
+ case QSsl::SslV3:
+ protectionLevel = SocketProtectionLevel_Ssl; // Only use this value if weak cipher support is required
+ break;
+ case QSsl::SecureProtocols:
+ case QSsl::TlsV1SslV3:
+ case QSsl::TlsV1_0:
+ protectionLevel = SocketProtectionLevel_Tls10;
+ break;
+ case QSsl::TlsV1_1:
+ protectionLevel = SocketProtectionLevel_Tls11;
+ break;
+ case QSsl::TlsV1_2:
+ protectionLevel = SocketProtectionLevel_Tls12;
+ break;
+ default:
+ protectionLevel = SocketProtectionLevel_Tls12; // default to highest
+ protocol = QSsl::TlsV1_2;
+ break;
+ }
+
+ // Sync custom certificates
+ const QSet<QSslCertificate> caCertificates = configuration.caCertificates.toSet();
+ const QSet<QSslCertificate> newCertificates = caCertificates - previousCaCertificates;
+ const QSet<QSslCertificate> oldCertificates = previousCaCertificates - caCertificates;
+ g->syncCaCertificates(newCertificates, oldCertificates);
+ previousCaCertificates = caCertificates;
+
+ continueHandshake();
+}
+
+void QSslSocketBackendPrivate::startServerEncryption()
+{
+ Q_UNIMPLEMENTED();
+}
+
+void QSslSocketBackendPrivate::transmit()
+{
+ Q_Q(QSslSocket);
+
+ if (connectionEncrypted && !writeBuffer.isEmpty()) {
+ qint64 totalBytesWritten = 0;
+ int nextDataBlockSize;
+ while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
+ int writtenBytes = plainSocket->write(writeBuffer.readPointer(), nextDataBlockSize);
+ writtenBytes = nextDataBlockSize;
+
+ writeBuffer.free(writtenBytes);
+ totalBytesWritten += writtenBytes;
+
+ if (writtenBytes < nextDataBlockSize)
+ break;
+ }
+
+ if (totalBytesWritten > 0) {
+ // Don't emit bytesWritten() recursively.
+ if (!emittedBytesWritten) {
+ emittedBytesWritten = true;
+ emit q->bytesWritten(totalBytesWritten);
+ emittedBytesWritten = false;
+ }
+ }
+ }
+
+ // Check if we've got any data to be read from the socket.
+ int pendingBytes;
+ bool bytesRead = false;
+ while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
+ char *ptr = buffer.reserve(pendingBytes);
+ int readBytes = plainSocket->read(ptr, pendingBytes);
+ buffer.chop(pendingBytes - readBytes);
+ bytesRead = true;
+ }
+
+ if (bytesRead) {
+ if (readyReadEmittedPointer)
+ *readyReadEmittedPointer = true;
+ emit q->readyRead();
+ }
+
+ if (pendingClose) {
+ pendingClose = false;
+ q->disconnectFromHost();
+ }
+}
+
+void QSslSocketBackendPrivate::disconnectFromHost()
+{
+ QMetaObject::invokeMethod(connectionHelper.data(), "disconnectSocketFromHost", Qt::QueuedConnection);
+}
+
+void QSslSocketBackendPrivate::disconnected()
+{
+}
+
+QSslCipher QSslSocketBackendPrivate::sessionCipher() const
+{
+ return configuration.sessionCipher;
+}
+
+QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
+{
+ return configuration.sessionCipher.protocol();
+}
+
+void QSslSocketBackendPrivate::continueHandshake()
+{
+ Q_Q(QSslSocket);
+
+ IStreamSocket *socket = reinterpret_cast<IStreamSocket *>(plainSocket->socketDescriptor());
+ if (qintptr(socket) == -1) {
+ q->setErrorString(QStringLiteral("At attempt was made to continue the handshake on an invalid socket."));
+ q->setSocketError(QAbstractSocket::SslInternalError);
+ emit q->error(QAbstractSocket::SslInternalError);
+ return;
+ }
+
+ HRESULT hr;
+ ComPtr<IHostName> hostName;
+ const QString host = verificationPeerName.isEmpty() ? plainSocket->peerName()
+ : verificationPeerName;
+ if (host.isEmpty()) {
+ ComPtr<IStreamSocketInformation> info;
+ hr = socket->get_Information(&info);
+ Q_ASSERT_SUCCEEDED(hr);
+ hr = info->get_RemoteAddress(&hostName);
+ } else {
+ HStringReference hostRef(reinterpret_cast<LPCWSTR>(host.utf16()), host.length());
+ hr = g->hostNameFactory->CreateHostName(hostRef.Get(), &hostName);
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+ if (FAILED(hr)) {
+ q->setErrorString(qt_error_string(hr));
+ q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
+ emit q->error(QAbstractSocket::SslInvalidUserDataError);
+ return;
+ }
+
+ ComPtr<IStreamSocketControl> control;
+ hr = socket->get_Control(&control);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<IStreamSocketControl2> control2;
+ hr = control.As(&control2);
+ ComPtr<IVector<ChainValidationResult>> ignoreList;
+ hr = control2->get_IgnorableServerCertificateErrors(&ignoreList);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ QSet<QSslError> ignoreErrors = ignoreErrorsList.toSet();
+ for (int i = ChainValidationResult_Untrusted; i < ChainValidationResult_OtherErrors + 1; ++i) {
+ // Populate the native ignore list - break to add, continue to skip
+ switch (i) {
+ case ChainValidationResult_Revoked:
+ case ChainValidationResult_InvalidSignature:
+ case ChainValidationResult_BasicConstraintsError:
+ case ChainValidationResult_InvalidCertificateAuthorityPolicy:
+ case ChainValidationResult_UnknownCriticalExtension:
+ case ChainValidationResult_OtherErrors:
+ continue; // The above errors can't be ignored in the handshake
+ case ChainValidationResult_Untrusted:
+ if (ignoreAllSslErrors || ignoreErrors.contains(QSslError::CertificateUntrusted))
+ break;
+ continue;
+ case ChainValidationResult_Expired:
+ if (ignoreAllSslErrors || ignoreErrors.contains(QSslError::CertificateExpired))
+ break;
+ continue;
+ case ChainValidationResult_IncompleteChain:
+ if (ignoreAllSslErrors
+ || ignoreErrors.contains(QSslError::InvalidCaCertificate)
+ || ignoreErrors.contains(QSslError::UnableToVerifyFirstCertificate)
+ || ignoreErrors.contains(QSslError::UnableToGetIssuerCertificate)) {
+ break;
+ }
+ continue;
+ case ChainValidationResult_WrongUsage:
+ if (ignoreAllSslErrors || ignoreErrors.contains(QSslError::InvalidPurpose))
+ break;
+ continue;
+ case ChainValidationResult_InvalidName:
+ if (ignoreAllSslErrors
+ || ignoreErrors.contains(QSslError::HostNameMismatch)
+ || ignoreErrors.contains(QSslError::SubjectIssuerMismatch)) {
+ break;
+ }
+ continue;
+ case ChainValidationResult_RevocationInformationMissing:
+ case ChainValidationResult_RevocationFailure:
+ default:
+ if (ignoreAllSslErrors)
+ break;
+ continue;
+ }
+ hr = ignoreList->Append(static_cast<ChainValidationResult>(i));
+ Q_ASSERT_SUCCEEDED(hr);
+ }
+
+ ComPtr<IAsyncAction> op;
+ hr = socket->UpgradeToSslAsync(protectionLevel, hostName.Get(), &op);
+ if (FAILED(hr)) {
+ q->setErrorString(QSslSocket::tr("Error creating SSL session: %1")
+ .arg(qt_error_string(hr)));
+ q->setSocketError(QAbstractSocket::SslInternalError);
+ emit q->error(QAbstractSocket::SslInternalError);
+ return;
+ }
+
+ hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(
+ this, &QSslSocketBackendPrivate::onSslUpgrade).Get());
+ Q_ASSERT_SUCCEEDED(hr);
+}
+
+HRESULT QSslSocketBackendPrivate::onSslUpgrade(IAsyncAction *action, AsyncStatus)
+{
+ Q_Q(QSslSocket);
+
+ if (wasDeleted) {
+ qWarning("SSL upgrade callback received after the delegate was deleted. "
+ "This may be indicative of an internal bug in the WinRT SSL implementation.");
+ return S_OK;
+ }
+
+ HRESULT hr = action->GetResults();
+ QSet<QSslError> errors;
+ switch (hr) {
+ case SEC_E_INVALID_TOKEN: // Occurs when the server doesn't support the requested protocol
+ q->setErrorString(qt_error_string(hr));
+ q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
+ emit q->error(QAbstractSocket::SslHandshakeFailedError);
+ q->disconnectFromHost();
+ return S_OK;
+ default:
+ if (FAILED(hr))
+ qErrnoWarning(hr, "error"); // Unhandled error; let sslErrors take care of it
+ break;
+ }
+
+ IStreamSocket *socket = reinterpret_cast<IStreamSocket *>(plainSocket->socketDescriptor());
+ if (qintptr(socket) == -1) {
+ qWarning("The underlying TCP socket used by the SSL socket is invalid. "
+ "This may be indicative of an internal bug in the WinRT SSL implementation.");
+ return S_OK;
+ }
+
+ ComPtr<IStreamSocketInformation> info;
+ hr = socket->get_Information(&info);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<IStreamSocketInformation2> info2;
+ hr = info.As(&info2);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ // Cipher
+ QSsl::SslProtocol protocol;
+ SocketProtectionLevel protectionLevel;
+ hr = info->get_ProtectionLevel(&protectionLevel);
+ switch (protectionLevel) {
+ default:
+ protocol = QSsl::UnknownProtocol;
+ break;
+ case SocketProtectionLevel_Ssl:
+ protocol = QSsl::SslV3;
+ break;
+ case SocketProtectionLevel_Tls10:
+ protocol = QSsl::TlsV1_0;
+ break;
+ case SocketProtectionLevel_Tls11:
+ protocol = QSsl::TlsV1_1;
+ break;
+ case SocketProtectionLevel_Tls12:
+ protocol = QSsl::TlsV1_2;
+ break;
+ }
+ configuration.sessionCipher = QSslCipher(QStringLiteral("WINRT"), protocol); // The actual cipher name is not accessible
+
+ // Certificate & chain
+ ComPtr<ICertificate> certificate;
+ hr = info2->get_ServerCertificate(&certificate);
+ Q_ASSERT_SUCCEEDED(hr);
+
+ QList<QSslCertificate> peerCertificateChain;
+ if (certificate) {
+ ComPtr<IAsyncOperation<CertificateChain *>> op;
+ hr = certificate->BuildChainAsync(Q_NULLPTR, &op);
+ Q_ASSERT_SUCCEEDED(hr);
+ ComPtr<ICertificateChain> certificateChain;
+ hr = QWinRTFunctions::await(op, certificateChain.GetAddressOf());
+ Q_ASSERT_SUCCEEDED(hr);
+
+ ComPtr<IVectorView<Certificate *>> certificates;
+ hr = certificateChain->GetCertificates(true, &certificates);
+ Q_ASSERT_SUCCEEDED(hr);
+ quint32 certificatesLength;
+ hr = certificates->get_Size(&certificatesLength);
+ Q_ASSERT_SUCCEEDED(hr);
+ for (quint32 i = 0; i < certificatesLength; ++i) {
+ ComPtr<ICertificate> chainCertificate;
+ hr = certificates->GetAt(i, &chainCertificate);
+ Q_ASSERT_SUCCEEDED(hr);
+ peerCertificateChain.append(QSslCertificatePrivate::QSslCertificate_from_Certificate(chainCertificate.Get()));
+ }
+ }
+
+ configuration.peerCertificate = certificate ? QSslCertificatePrivate::QSslCertificate_from_Certificate(certificate.Get())
+ : QSslCertificate();
+ configuration.peerCertificateChain = peerCertificateChain;
+
+ // Errors
+ ComPtr<IVectorView<ChainValidationResult>> chainValidationResults;
+ hr = info2->get_ServerCertificateErrors(&chainValidationResults);
+ Q_ASSERT_SUCCEEDED(hr);
+ quint32 size;
+ hr = chainValidationResults->get_Size(&size);
+ Q_ASSERT_SUCCEEDED(hr);
+ for (quint32 i = 0; i < size; ++i) {
+ ChainValidationResult result;
+ hr = chainValidationResults->GetAt(i, &result);
+ Q_ASSERT_SUCCEEDED(hr);
+ switch (result) {
+ case ChainValidationResult_Success:
+ break;
+ case ChainValidationResult_Untrusted:
+ errors.insert(QSslError::CertificateUntrusted);
+ break;
+ case ChainValidationResult_Revoked:
+ errors.insert(QSslError::CertificateRevoked);
+ break;
+ case ChainValidationResult_Expired:
+ errors.insert(QSslError::CertificateExpired);
+ break;
+ case ChainValidationResult_IncompleteChain:
+ errors.insert(QSslError::UnableToGetIssuerCertificate);
+ break;
+ case ChainValidationResult_InvalidSignature:
+ errors.insert(QSslError::CertificateSignatureFailed);
+ break;
+ case ChainValidationResult_WrongUsage:
+ errors.insert(QSslError::InvalidPurpose);
+ break;
+ case ChainValidationResult_InvalidName:
+ errors.insert(QSslError::HostNameMismatch);
+ break;
+ case ChainValidationResult_InvalidCertificateAuthorityPolicy:
+ errors.insert(QSslError::InvalidCaCertificate);
+ break;
+ default:
+ errors.insert(QSslError::UnspecifiedError);
+ break;
+ }
+ }
+
+ sslErrors = errors.toList();
+
+ // Peer validation
+ if (!configuration.peerCertificate.isNull()) {
+ const QString peerName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
+ if (!isMatchingHostname(configuration.peerCertificate, peerName)) {
+ // No matches in common names or alternate names.
+ const QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
+ const int index = sslErrors.indexOf(QSslError::HostNameMismatch);
+ if (index >= 0) // Replace the existing error
+ sslErrors[index] = error;
+ else
+ sslErrors.append(error);
+ emit q->peerVerifyError(error);
+ }
+
+ // Peer validation required, but no certificate is present
+ } else if (configuration.peerVerifyMode == QSslSocket::VerifyPeer
+ || configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer) {
+ QSslError error(QSslError::NoPeerCertificate);
+ sslErrors.append(error);
+ emit q->peerVerifyError(error);
+ }
+
+ // Peer chain validation
+ foreach (const QSslCertificate &certificate, peerCertificateChain) {
+ if (!QSslCertificatePrivate::isBlacklisted(certificate))
+ continue;
+
+ QSslError error(QSslError::CertificateBlacklisted, certificate);
+ sslErrors.append(error);
+ emit q->peerVerifyError(error);
+ }
+
+ if (!sslErrors.isEmpty()) {
+ emit q->sslErrors(sslErrors);
+ q->setErrorString(sslErrors.first().errorString());
+ q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
+ emit q->error(QAbstractSocket::SslHandshakeFailedError);
+
+ // Disconnect if there are any non-ignorable errors
+ foreach (const QSslError &error, sslErrors) {
+ if (ignoreErrorsList.contains(error))
+ continue;
+ q->disconnectFromHost();
+ return S_OK;
+ }
+ }
+
+ if (readBufferMaxSize)
+ plainSocket->setReadBufferSize(readBufferMaxSize);
+
+ connectionEncrypted = true;
+ emit q->encrypted();
+
+ if (pendingClose) {
+ pendingClose = false;
+ q->disconnectFromHost();
+ }
+
+ return S_OK;
+}
+
+QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certificateChain, const QString &hostName)
+{
+ Q_UNIMPLEMENTED();
+ Q_UNUSED(certificateChain)
+ Q_UNUSED(hostName)
+ QList<QSslError> errors;
+
+ return errors;
+}
+
+bool QSslSocketBackendPrivate::importPKCS12(QIODevice *device,
+ QSslKey *key, QSslCertificate *cert,
+ QList<QSslCertificate> *caCertificates,
+ const QByteArray &passPhrase)
+{
+ Q_UNIMPLEMENTED();
+ Q_UNUSED(device)
+ Q_UNUSED(key)
+ Q_UNUSED(cert)
+ Q_UNUSED(caCertificates)
+ Q_UNUSED(passPhrase)
+ return false;
+}
+
+QT_END_NAMESPACE
diff --git a/src/network/ssl/qsslsocket_winrt_p.h b/src/network/ssl/qsslsocket_winrt_p.h
new file mode 100644
index 0000000000..aa31c85d6e
--- /dev/null
+++ b/src/network/ssl/qsslsocket_winrt_p.h
@@ -0,0 +1,111 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtNetwork module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QSSLSOCKET_WINRT_P_H
+#define QSSLSOCKET_WINRT_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of the QtNetwork library. This header file may change from
+// version to version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "qsslsocket_p.h"
+
+#include <wrl.h>
+#include <windows.networking.sockets.h>
+
+QT_BEGIN_NAMESPACE
+
+class QSslSocketConnectionHelper : public QObject
+{
+ Q_OBJECT
+public:
+ QSslSocketConnectionHelper(QSslSocketBackendPrivate *d)
+ : d(d) { }
+
+ Q_INVOKABLE void disconnectSocketFromHost();
+
+private:
+ QSslSocketBackendPrivate *d;
+};
+
+class QSslSocketBackendPrivate : public QSslSocketPrivate
+{
+ Q_DECLARE_PUBLIC(QSslSocket)
+public:
+ QSslSocketBackendPrivate();
+ ~QSslSocketBackendPrivate();
+
+ // Platform specific functions
+ void startClientEncryption() Q_DECL_OVERRIDE;
+ void startServerEncryption() Q_DECL_OVERRIDE;
+ void transmit() Q_DECL_OVERRIDE;
+ void disconnectFromHost() Q_DECL_OVERRIDE;
+ void disconnected() Q_DECL_OVERRIDE;
+ QSslCipher sessionCipher() const Q_DECL_OVERRIDE;
+ QSsl::SslProtocol sessionProtocol() const Q_DECL_OVERRIDE;
+ void continueHandshake() Q_DECL_OVERRIDE;
+
+ static QList<QSslCipher> defaultCiphers();
+ static QList<QSslError> verify(QList<QSslCertificate> certificateChain, const QString &hostName);
+ static bool importPKCS12(QIODevice *device,
+ QSslKey *key, QSslCertificate *cert,
+ QList<QSslCertificate> *caCertificates,
+ const QByteArray &passPhrase);
+
+private:
+ HRESULT onSslUpgrade(ABI::Windows::Foundation::IAsyncAction *,
+ ABI::Windows::Foundation::AsyncStatus);
+
+ QScopedPointer<QSslSocketConnectionHelper> connectionHelper;
+ ABI::Windows::Networking::Sockets::SocketProtectionLevel protectionLevel;
+ QSet<QSslCertificate> previousCaCertificates;
+};
+
+QT_END_NAMESPACE
+
+#endif // QSSLSOCKET_WINRT_P_H
diff --git a/src/network/ssl/ssl.pri b/src/network/ssl/ssl.pri
index eb8268515e..384e149241 100644
--- a/src/network/ssl/ssl.pri
+++ b/src/network/ssl/ssl.pri
@@ -1,32 +1,49 @@
# OpenSSL support; compile in QSslSocket.
-contains(QT_CONFIG, openssl) | contains(QT_CONFIG, openssl-linked) {
- HEADERS += ssl/qssl.h \
+contains(QT_CONFIG, ssl) | contains(QT_CONFIG, openssl) | contains(QT_CONFIG, openssl-linked) {
+ HEADERS += ssl/qasn1element_p.h \
+ ssl/qssl.h \
ssl/qsslcertificate.h \
ssl/qsslcertificate_p.h \
- ssl/qsslconfiguration.h \
+ ssl/qsslconfiguration.h \
ssl/qsslconfiguration_p.h \
ssl/qsslcipher.h \
ssl/qsslcipher_p.h \
ssl/qsslerror.h \
ssl/qsslkey.h \
+ ssl/qsslkey_p.h \
ssl/qsslsocket.h \
- ssl/qsslsocket_openssl_p.h \
- ssl/qsslsocket_openssl_symbols_p.h \
ssl/qsslsocket_p.h \
ssl/qsslcertificateextension.h \
- ssl/qsslcertificateextension_p.h \
- ssl/qsslcontext_p.h
- SOURCES += ssl/qssl.cpp \
+ ssl/qsslcertificateextension_p.h
+ SOURCES += ssl/qasn1element.cpp \
+ ssl/qssl.cpp \
ssl/qsslcertificate.cpp \
- ssl/qsslconfiguration.cpp \
+ ssl/qsslconfiguration.cpp \
ssl/qsslcipher.cpp \
+ ssl/qsslkey_p.cpp \
ssl/qsslerror.cpp \
- ssl/qsslkey.cpp \
ssl/qsslsocket.cpp \
+ ssl/qsslcertificateextension.cpp
+
+ winrt {
+ HEADERS += ssl/qsslsocket_winrt_p.h
+ SOURCES += ssl/qsslcertificate_qt.cpp \
+ ssl/qsslcertificate_winrt.cpp \
+ ssl/qsslkey_qt.cpp \
+ ssl/qsslkey_winrt.cpp \
+ ssl/qsslsocket_winrt.cpp
+ }
+}
+
+contains(QT_CONFIG, openssl) | contains(QT_CONFIG, openssl-linked) {
+ HEADERS += ssl/qsslcontext_openssl_p.h \
+ ssl/qsslsocket_openssl_p.h \
+ ssl/qsslsocket_openssl_symbols_p.h
+ SOURCES += ssl/qsslcertificate_openssl.cpp \
+ ssl/qsslcontext_openssl.cpp \
+ ssl/qsslkey_openssl.cpp \
ssl/qsslsocket_openssl.cpp \
- ssl/qsslsocket_openssl_symbols.cpp \
- ssl/qsslcertificateextension.cpp \
- ssl/qsslcontext.cpp
+ ssl/qsslsocket_openssl_symbols.cpp
android:!android-no-sdk: SOURCES += ssl/qsslsocket_openssl_android.cpp