diff options
Diffstat (limited to 'src/core/net')
36 files changed, 1545 insertions, 1963 deletions
diff --git a/src/core/net/client_cert_override.cpp b/src/core/net/client_cert_override.cpp deleted file mode 100644 index f33515f63..000000000 --- a/src/core/net/client_cert_override.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2018 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "client_cert_override.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/task/post_task.h" -#include "base/callback_forward.h" -#include "content/public/browser/browser_task_traits.h" -#include "net/ssl/client_cert_store.h" -#include "net/ssl/ssl_cert_request_info.h" -#include "net/ssl/ssl_private_key.h" -#include "net/cert/x509_certificate.h" -#include "third_party/boringssl/src/include/openssl/pem.h" -#include "third_party/boringssl/src/include/openssl/err.h" -#include "third_party/boringssl/src/include/openssl/evp.h" - -#include "client_cert_store_data.h" -#include "profile_io_data_qt.h" - -#include <QtNetwork/qtnetworkglobal.h> - -#if defined(USE_NSS_CERTS) -#include "net/ssl/client_cert_store_nss.h" -#endif - -#if defined(OS_WIN) -#include "net/ssl/client_cert_store_win.h" -#endif - -#if defined(OS_MACOSX) -#include "net/ssl/client_cert_store_mac.h" -#endif - -namespace { - -class ClientCertIdentityOverride : public net::ClientCertIdentity -{ -public: - ClientCertIdentityOverride(scoped_refptr<net::X509Certificate> cert, scoped_refptr<net::SSLPrivateKey> key) - : net::ClientCertIdentity(std::move(cert)), m_key(std::move(key)) {} - ~ClientCertIdentityOverride() override = default; - - void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<net::SSLPrivateKey>)> private_key_callback) override - { - std::move(private_key_callback).Run(m_key); - } - -#if defined(OS_MACOSX) - SecIdentityRef sec_identity_ref() const override - { - return nullptr; - } -#endif - -private: - scoped_refptr<net::SSLPrivateKey> m_key; -}; - -} // namespace - -namespace QtWebEngineCore { - -ClientCertOverrideStore::ClientCertOverrideStore(ClientCertificateStoreData *storeData) - : ClientCertStore() - , m_storeData(storeData) - , m_nativeStore(createNativeStore()) -{ -} - -ClientCertOverrideStore::~ClientCertOverrideStore() = default; - -#if QT_CONFIG(ssl) -net::ClientCertIdentityList ClientCertOverrideStore::GetClientCertsOnUIThread(const net::SSLCertRequestInfo &cert_request_info) -{ - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - const auto &clientCertOverrideData = m_storeData->extraCerts; - // Look for certificates in memory store - for (int i = 0; i < clientCertOverrideData.length(); i++) { - scoped_refptr<net::X509Certificate> cert = clientCertOverrideData[i]->certPtr; - if (cert != NULL && cert->IsIssuedByEncoded(cert_request_info.cert_authorities)) { - net::ClientCertIdentityList selected_identities; - selected_identities.push_back(std::make_unique<ClientCertIdentityOverride>(cert, clientCertOverrideData[i]->keyPtr)); - return selected_identities; - } - } - return net::ClientCertIdentityList(); -} - -void ClientCertOverrideStore::GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info, - ClientCertListCallback callback, - net::ClientCertIdentityList &&result) -{ - // Continue with native cert store if matching certificatse were not found in memory - if (result.empty() && m_nativeStore) - m_nativeStore->GetClientCerts(cert_request_info, std::move(callback)); - else - std::move(callback).Run(std::move(result)); -} - -#endif // QT_CONFIG(ssl) - -void ClientCertOverrideStore::GetClientCerts(const net::SSLCertRequestInfo &cert_request_info, - ClientCertListCallback callback) -{ -#if QT_CONFIG(ssl) - // Access the user-provided data from the UI thread, but return on whatever thread this is. - if (base::PostTaskAndReplyWithResult( - FROM_HERE, { content::BrowserThread::UI }, - base::BindOnce(&ClientCertOverrideStore::GetClientCertsOnUIThread, - base::Unretained(this), std::cref(cert_request_info)), - base::BindOnce(&ClientCertOverrideStore::GetClientCertsReturn, - base::Unretained(this), std::cref(cert_request_info), std::move(callback))) - ) { - return; - } -#endif // QT_CONFIG(ssl) - - // Continue with native cert store if we failed to post task - if (m_nativeStore) - m_nativeStore->GetClientCerts(cert_request_info, std::move(callback)); - else - std::move(callback).Run(net::ClientCertIdentityList()); -} - -// static -std::unique_ptr<net::ClientCertStore> ClientCertOverrideStore::createNativeStore() -{ -#if defined(USE_NSS_CERTS) - return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(net::ClientCertStoreNSS::PasswordDelegateFactory())); -#elif defined(OS_WIN) - return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin()); -#elif defined(OS_MACOSX) - return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac()); -#else - return nullptr; -#endif -} -} // namespace QtWebEngineCore diff --git a/src/core/net/client_cert_override.h b/src/core/net/client_cert_override.h deleted file mode 100644 index 7fd28eaeb..000000000 --- a/src/core/net/client_cert_override.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2018 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CLIENT_CERT_OVERRIDE_P_H -#define CLIENT_CERT_OVERRIDE_P_H - -#include "net/ssl/client_cert_store.h" -#include "base/callback_forward.h" -#include "net/cert/x509_certificate.h" - -namespace net { -class SSLCertRequestInfo; -} // namespace net - -namespace QtWebEngineCore { -struct ClientCertificateStoreData; - -class ClientCertOverrideStore : public net::ClientCertStore -{ -public: - ClientCertOverrideStore(ClientCertificateStoreData *storeData); - virtual ~ClientCertOverrideStore() override; - void GetClientCerts(const net::SSLCertRequestInfo &cert_request_info, - ClientCertListCallback callback) override; -private: - static std::unique_ptr<net::ClientCertStore> createNativeStore(); - net::ClientCertIdentityList GetClientCertsOnUIThread(const net::SSLCertRequestInfo &request); - void GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info, - ClientCertListCallback callback, - net::ClientCertIdentityList &&result); - ClientCertificateStoreData *m_storeData; - std::unique_ptr<net::ClientCertStore> m_nativeStore; -}; - -} // QtWebEngineCore - -#endif diff --git a/src/core/net/client_cert_qt.cpp b/src/core/net/client_cert_qt.cpp new file mode 100644 index 000000000..044e5618e --- /dev/null +++ b/src/core/net/client_cert_qt.cpp @@ -0,0 +1,148 @@ +// Copyright (C) 2018 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client_cert_qt.h" + +#include "base/functional/bind.h" +#include "base/functional/callback_forward.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/browser_task_traits.h" +#include "crypto/crypto_buildflags.h" +#include "net/ssl/client_cert_store.h" +#include "net/ssl/ssl_cert_request_info.h" +#include "net/ssl/ssl_private_key.h" +#include "net/cert/x509_certificate.h" +#include "third_party/boringssl/src/include/openssl/pem.h" +#include "third_party/boringssl/src/include/openssl/err.h" +#include "third_party/boringssl/src/include/openssl/evp.h" + +#include "client_cert_store_data.h" + +#include <QtNetwork/qtnetworkglobal.h> + +#if BUILDFLAG(USE_NSS_CERTS) +#include "net/ssl/client_cert_store_nss.h" +#endif + +#if defined(Q_OS_WIN) +#include "net/ssl/client_cert_store_win.h" +#endif + +#if BUILDFLAG(IS_MAC) +#include "net/ssl/client_cert_store_mac.h" +#endif + +namespace { + +class ClientCertIdentityQt : public net::ClientCertIdentity +{ +public: + ClientCertIdentityQt(scoped_refptr<net::X509Certificate> cert, scoped_refptr<net::SSLPrivateKey> key) + : net::ClientCertIdentity(std::move(cert)), m_key(std::move(key)) {} + ~ClientCertIdentityQt() override = default; + + void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<net::SSLPrivateKey>)> private_key_callback) override + { + std::move(private_key_callback).Run(m_key); + } + +private: + scoped_refptr<net::SSLPrivateKey> m_key; +}; + +} // namespace + +namespace QtWebEngineCore { + +ClientCertStoreQt::ClientCertStoreQt(ClientCertificateStoreData *storeData) + : ClientCertStore() + , m_storeData(storeData) + , m_nativeStore(createNativeStore()) +{ +} + +ClientCertStoreQt::~ClientCertStoreQt() = default; + +#if QT_CONFIG(ssl) +net::ClientCertIdentityList ClientCertStoreQt::GetClientCertsOnUIThread(const net::SSLCertRequestInfo &cert_request_info) +{ + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + const auto &clientCertOverrideData = m_storeData->extraCerts; + + // Look for certificates in memory store + net::ClientCertIdentityList selected_identities; + for (int i = 0; i < clientCertOverrideData.length(); i++) { + scoped_refptr<net::X509Certificate> cert = clientCertOverrideData[i]->certPtr; + if (cert) { + if (cert->HasExpired()) { + qWarning() << "Expired certificate" << clientCertOverrideData[i]; + continue; + } + if (cert_request_info.cert_authorities.empty() + || cert->IsIssuedByEncoded(cert_request_info.cert_authorities)) { + selected_identities.push_back(std::make_unique<ClientCertIdentityQt>( + cert, clientCertOverrideData[i]->keyPtr)); + } + } + } + return selected_identities; +} + +void ClientCertStoreQt::GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info, + ClientCertListCallback callback, + net::ClientCertIdentityList &&result) +{ + // Continue with native cert store and append them after memory certificates + if (m_nativeStore) { + ClientCertListCallback callback2 = base::BindOnce( + [](ClientCertStoreQt::ClientCertListCallback callback, + net::ClientCertIdentityList result1, net::ClientCertIdentityList result2) { + while (!result2.empty()) { + result1.push_back(std::move(result2.back())); + result2.pop_back(); + } + std::move(callback).Run(std::move(result1)); + }, + std::move(callback), std::move(result)); + m_nativeStore->GetClientCerts(cert_request_info, std::move(callback2)); + } else { + std::move(callback).Run(std::move(result)); + } +} + +#endif // QT_CONFIG(ssl) + +void ClientCertStoreQt::GetClientCerts(const net::SSLCertRequestInfo &cert_request_info, + ClientCertListCallback callback) +{ +#if QT_CONFIG(ssl) + // Access the user-provided data from the UI thread, but return on whatever thread this is. + bool ok = content::GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&ClientCertStoreQt::GetClientCertsOnUIThread, + base::Unretained(this), std::cref(cert_request_info)), + base::BindOnce(&ClientCertStoreQt::GetClientCertsReturn, + base::Unretained(this), std::cref(cert_request_info), std::move(callback))); + DCHECK(ok); // callback is already moved and we can't really recover here. +#else + if (m_nativeStore) + m_nativeStore->GetClientCerts(cert_request_info, std::move(callback)); + else + std::move(callback).Run(net::ClientCertIdentityList()); +#endif // QT_CONFIG(ssl) +} + +// static +std::unique_ptr<net::ClientCertStore> ClientCertStoreQt::createNativeStore() +{ +#if BUILDFLAG(USE_NSS_CERTS) + return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(net::ClientCertStoreNSS::PasswordDelegateFactory())); +#elif defined(Q_OS_WIN) + return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin()); +#elif BUILDFLAG(IS_MAC) + return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac()); +#else + return nullptr; +#endif +} +} // namespace QtWebEngineCore diff --git a/src/core/net/client_cert_qt.h b/src/core/net/client_cert_qt.h new file mode 100644 index 000000000..96579fae6 --- /dev/null +++ b/src/core/net/client_cert_qt.h @@ -0,0 +1,37 @@ +// Copyright (C) 2018 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef CLIENT_CERT_QT_P_H +#define CLIENT_CERT_QT_P_H + +#include "base/functional/callback_forward.h" +#include "net/cert/x509_certificate.h" +#include "net/ssl/client_cert_store.h" + +namespace net { +class SSLCertRequestInfo; +} // namespace net + +namespace QtWebEngineCore { +struct ClientCertificateStoreData; + +class ClientCertStoreQt : public net::ClientCertStore +{ +public: + ClientCertStoreQt(ClientCertificateStoreData *storeData); + virtual ~ClientCertStoreQt() override; + void GetClientCerts(const net::SSLCertRequestInfo &cert_request_info, + ClientCertListCallback callback) override; +private: + static std::unique_ptr<net::ClientCertStore> createNativeStore(); + net::ClientCertIdentityList GetClientCertsOnUIThread(const net::SSLCertRequestInfo &request); + void GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info, + ClientCertListCallback callback, + net::ClientCertIdentityList &&result); + ClientCertificateStoreData *m_storeData; + std::unique_ptr<net::ClientCertStore> m_nativeStore; +}; + +} // QtWebEngineCore + +#endif diff --git a/src/core/net/client_cert_store_data.cpp b/src/core/net/client_cert_store_data.cpp index 314e64145..0de6885df 100644 --- a/src/core/net/client_cert_store_data.cpp +++ b/src/core/net/client_cert_store_data.cpp @@ -1,48 +1,9 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "net/client_cert_store_data.h" #if QT_CONFIG(ssl) -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" #include "net/base/net_errors.h" #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_platform_key_util.h" @@ -59,16 +20,16 @@ namespace { -class SSLPlatformKeyOverride : public net::ThreadedSSLPrivateKey::Delegate +class SSLPlatformKeyQt : public net::ThreadedSSLPrivateKey::Delegate { public: - SSLPlatformKeyOverride(const QByteArray &sslKeyInBytes) + SSLPlatformKeyQt(const QByteArray &sslKeyInBytes) { m_mem = BIO_new_mem_buf(sslKeyInBytes, -1); m_key = PEM_read_bio_PrivateKey(m_mem, nullptr, nullptr, nullptr); } - ~SSLPlatformKeyOverride() override + ~SSLPlatformKeyQt() override { if (m_key) EVP_PKEY_free(m_key); @@ -104,8 +65,8 @@ public: std::vector<uint16_t> GetAlgorithmPreferences() override { - return { SSL_SIGN_RSA_PKCS1_SHA1, SSL_SIGN_RSA_PKCS1_SHA512 - , SSL_SIGN_RSA_PKCS1_SHA384, SSL_SIGN_RSA_PKCS1_SHA256 }; + return net::SSLPrivateKey::DefaultAlgorithmPreferences(EVP_PKEY_id(m_key), + /* supports pss */ true); } std::string GetProviderName() override { return "qtwebengine"; @@ -113,8 +74,6 @@ public: private: EVP_PKEY *m_key; BIO *m_mem; - - DISALLOW_COPY_AND_ASSIGN(SSLPlatformKeyOverride); }; scoped_refptr<net::SSLPrivateKey> wrapOpenSSLPrivateKey(const QByteArray &sslKeyInBytes) @@ -123,7 +82,7 @@ scoped_refptr<net::SSLPrivateKey> wrapOpenSSLPrivateKey(const QByteArray &sslKey return nullptr; return base::MakeRefCounted<net::ThreadedSSLPrivateKey>( - std::make_unique<SSLPlatformKeyOverride>(sslKeyInBytes), + std::make_unique<SSLPlatformKeyQt>(sslKeyInBytes), net::GetSSLPlatformKeyTaskRunner()); } @@ -138,7 +97,8 @@ void ClientCertificateStoreData::add(const QSslCertificate &certificate, const Q Entry *data = new Entry; data->keyPtr = wrapOpenSSLPrivateKey(sslKeyInBytes); - data->certPtr = net::X509Certificate::CreateFromBytes(certInBytes.data(), certInBytes.length()); + data->certPtr = net::X509Certificate::CreateFromBytes(base::make_span((const unsigned char *)certInBytes.data(), + (unsigned long)certInBytes.length())); data->key = privateKey; data->certificate = certificate; extraCerts.append(data); diff --git a/src/core/net/client_cert_store_data.h b/src/core/net/client_cert_store_data.h index 4976ac936..c2e28ac18 100644 --- a/src/core/net/client_cert_store_data.h +++ b/src/core/net/client_cert_store_data.h @@ -1,47 +1,11 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef CLIENT_CERT_STORE_DATA_H #define CLIENT_CERT_STORE_DATA_H -#include "qtwebenginecoreglobal.h" -#include "qtnetworkglobal.h" +#include <QtWebEngineCore/qtwebenginecoreglobal.h> +#include <QtNetwork/qtnetworkglobal.h> #if QT_CONFIG(ssl) #include "base/memory/ref_counted.h" diff --git a/src/core/net/cookie_monster_delegate_qt.cpp b/src/core/net/cookie_monster_delegate_qt.cpp index a7a3a9348..d107c520c 100644 --- a/src/core/net/cookie_monster_delegate_qt.cpp +++ b/src/core/net/cookie_monster_delegate_qt.cpp @@ -1,50 +1,9 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "cookie_monster_delegate_qt.h" -#include "base/bind.h" -#include "base/memory/ptr_util.h" -#include "base/task/post_task.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "base/functional/bind.h" #include "net/cookies/cookie_util.h" #include "services/network/public/mojom/cookie_manager.mojom.h" @@ -52,6 +11,8 @@ #include "api/qwebenginecookiestore_p.h" #include "type_conversion.h" +#include <QNetworkCookie> + namespace QtWebEngineCore { class CookieChangeListener : public network::mojom::CookieChangeListener @@ -68,8 +29,6 @@ public: private: CookieMonsterDelegateQt *m_delegate; - - DISALLOW_COPY_AND_ASSIGN(CookieChangeListener); }; class CookieAccessFilter : public network::mojom::CookieRemoteAccessFilter @@ -80,14 +39,12 @@ public: void AllowedAccess(const GURL &url, const net::SiteForCookies &site_for_cookies, AllowedAccessCallback callback) override { - bool allow = m_delegate->canGetCookies(toQt(site_for_cookies.RepresentativeUrl()), toQt(url)); + bool allow = m_delegate->canGetCookies(toQt(site_for_cookies.first_party_url()), toQt(url)); std::move(callback).Run(allow); } private: CookieMonsterDelegateQt *m_delegate; - - DISALLOW_COPY_AND_ASSIGN(CookieAccessFilter); }; @@ -126,32 +83,30 @@ bool CookieMonsterDelegateQt::hasCookieMonster() return m_mojoCookieManager.is_bound(); } -void CookieMonsterDelegateQt::getAllCookies(quint64 callbackId) +void CookieMonsterDelegateQt::getAllCookies() { - m_mojoCookieManager->GetAllCookies(base::BindOnce(&CookieMonsterDelegateQt::GetAllCookiesCallbackOnUIThread, this, callbackId)); + m_mojoCookieManager->GetAllCookies(net::CookieStore::GetAllCookiesCallback()); } -void CookieMonsterDelegateQt::setCookie(quint64 callbackId, const QNetworkCookie &cookie, const QUrl &origin) +void CookieMonsterDelegateQt::setCookie(const QNetworkCookie &cookie, const QUrl &origin) { Q_ASSERT(hasCookieMonster()); Q_ASSERT(m_client); - net::CookieStore::SetCookiesCallback callback; - GURL gurl = origin.isEmpty() ? sourceUrlForCookie(cookie) : toGurl(origin); std::string cookie_line = cookie.toRawForm().toStdString(); - if (callbackId != CallbackDirectory::NoCallbackId) - callback = base::BindOnce(&CookieMonsterDelegateQt::SetCookieCallbackOnUIThread, this, callbackId); - net::CanonicalCookie::CookieInclusionStatus inclusion; - auto canonCookie = net::CanonicalCookie::Create(gurl, cookie_line, base::Time::Now(), base::nullopt, &inclusion); - if (!inclusion.IsInclude()) { + net::CookieInclusionStatus inclusion; + auto canonCookie = net::CanonicalCookie::Create(gurl, cookie_line, base::Time::Now(), + absl::nullopt, absl::nullopt, true, &inclusion); + if (!canonCookie || !inclusion.IsInclude()) { LOG(WARNING) << "QWebEngineCookieStore::setCookie() - Tried to set invalid cookie"; return; } net::CookieOptions options; options.set_include_httponly(); - m_mojoCookieManager->SetCanonicalCookie(*canonCookie.get(), gurl.scheme(), options, std::move(callback)); + options.set_same_site_cookie_context(net::CookieOptions::SameSiteCookieContext::MakeInclusiveForSet()); + m_mojoCookieManager->SetCanonicalCookie(*canonCookie.get(), gurl, options, net::CookieStore::SetCookiesCallback()); } void CookieMonsterDelegateQt::deleteCookie(const QNetworkCookie &cookie, const QUrl &origin) @@ -167,30 +122,26 @@ void CookieMonsterDelegateQt::deleteCookie(const QNetworkCookie &cookie, const Q m_mojoCookieManager->DeleteCookies(std::move(filter), network::mojom::CookieManager::DeleteCookiesCallback()); } -void CookieMonsterDelegateQt::deleteSessionCookies(quint64 callbackId) +void CookieMonsterDelegateQt::deleteSessionCookies() { Q_ASSERT(hasCookieMonster()); Q_ASSERT(m_client); - network::mojom::CookieManager::DeleteCookiesCallback callback = - base::BindOnce(&CookieMonsterDelegateQt::DeleteCookiesCallbackOnUIThread, this, callbackId); auto filter = network::mojom::CookieDeletionFilter::New(); filter->session_control = network::mojom::CookieDeletionSessionControl::SESSION_COOKIES; - m_mojoCookieManager->DeleteCookies(std::move(filter), std::move(callback)); + m_mojoCookieManager->DeleteCookies(std::move(filter), network::mojom::CookieManager::DeleteCookiesCallback()); } -void CookieMonsterDelegateQt::deleteAllCookies(quint64 callbackId) +void CookieMonsterDelegateQt::deleteAllCookies() { Q_ASSERT(hasCookieMonster()); Q_ASSERT(m_client); - network::mojom::CookieManager::DeleteCookiesCallback callback = - base::BindOnce(&CookieMonsterDelegateQt::DeleteCookiesCallbackOnUIThread, this, callbackId); auto filter = network::mojom::CookieDeletionFilter::New(); - m_mojoCookieManager->DeleteCookies(std::move(filter), std::move(callback)); + m_mojoCookieManager->DeleteCookies(std::move(filter), network::mojom::CookieManager::DeleteCookiesCallback()); } -void CookieMonsterDelegateQt::setMojoCookieManager(network::mojom::CookieManagerPtrInfo cookie_manager_info) +void CookieMonsterDelegateQt::setMojoCookieManager(mojo::PendingRemote<network::mojom::CookieManager> cookie_manager_info) { if (m_mojoCookieManager.is_bound()) unsetMojoCookieManager(); @@ -265,23 +216,4 @@ void CookieMonsterDelegateQt::OnCookieChanged(const net::CookieChangeInfo &chang m_client->d_func()->onCookieChanged(toQt(change.cookie), change.cause != net::CookieChangeCause::INSERTED); } -void CookieMonsterDelegateQt::GetAllCookiesCallbackOnUIThread(qint64 callbackId, const net::CookieList &cookies) -{ - QByteArray rawCookies = QByteArray::fromStdString(net::CanonicalCookie::BuildCookieLine(cookies)); - if (m_client) - m_client->d_func()->onGetAllCallbackResult(callbackId, rawCookies); -} - -void CookieMonsterDelegateQt::SetCookieCallbackOnUIThread(qint64 callbackId, net::CanonicalCookie::CookieInclusionStatus status) -{ - if (m_client) - m_client->d_func()->onSetCallbackResult(callbackId, status.IsInclude()); -} - -void CookieMonsterDelegateQt::DeleteCookiesCallbackOnUIThread(qint64 callbackId, uint numCookies) -{ - if (m_client) - m_client->d_func()->onDeleteCallbackResult(callbackId, numCookies); -} - } // namespace QtWebEngineCore diff --git a/src/core/net/cookie_monster_delegate_qt.h b/src/core/net/cookie_monster_delegate_qt.h index a8432e125..f6872323d 100644 --- a/src/core/net/cookie_monster_delegate_qt.h +++ b/src/core/net/cookie_monster_delegate_qt.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // // W A R N I N G @@ -60,7 +24,7 @@ #endif #include "base/memory/ref_counted.h" #include "mojo/public/cpp/bindings/receiver.h" -#include "net/cookies/cookie_change_dispatcher.h" +#include "mojo/public/cpp/bindings/remote.h" #include "net/cookies/cookie_store.h" #include "services/network/public/mojom/cookie_manager.mojom-forward.h" #include "services/network/public/mojom/cookie_manager.mojom.h" @@ -69,21 +33,21 @@ #undef StAsH_signals #endif -#include <QNetworkCookie> #include <QPointer> +QT_FORWARD_DECLARE_CLASS(QNetworkCookie) QT_FORWARD_DECLARE_CLASS(QWebEngineCookieStore) namespace QtWebEngineCore { class CookieMonsterDelegateQtPrivate; -class Q_WEBENGINECORE_PRIVATE_EXPORT CookieMonsterDelegateQt : public base::RefCountedThreadSafe<CookieMonsterDelegateQt> +class Q_WEBENGINECORE_EXPORT CookieMonsterDelegateQt : public base::RefCountedThreadSafe<CookieMonsterDelegateQt> { QPointer<QWebEngineCookieStore> m_client; std::vector<std::unique_ptr<net::CookieChangeSubscription>> m_subscriptions; - network::mojom::CookieManagerPtr m_mojoCookieManager; + mojo::Remote<network::mojom::CookieManager> m_mojoCookieManager; std::unique_ptr<network::mojom::CookieChangeListener> m_listener; std::unique_ptr<network::mojom::CookieRemoteAccessFilter> m_filter; mojo::Receiver<network::mojom::CookieChangeListener> m_receiver; @@ -95,14 +59,14 @@ public: bool hasCookieMonster(); - void setCookie(quint64 callbackId, const QNetworkCookie &cookie, const QUrl &origin); + void setCookie(const QNetworkCookie &cookie, const QUrl &origin); void deleteCookie(const QNetworkCookie &cookie, const QUrl &origin); - void getAllCookies(quint64 callbackId); - void deleteSessionCookies(quint64 callbackId); - void deleteAllCookies(quint64 callbackId); + void getAllCookies(); + void deleteSessionCookies(); + void deleteAllCookies(); void setClient(QWebEngineCookieStore *client); - void setMojoCookieManager(network::mojom::CookieManagerPtrInfo cookie_manager_info); + void setMojoCookieManager(mojo::PendingRemote<network::mojom::CookieManager> cookie_manager_info); void unsetMojoCookieManager(); void setHasFilter(bool b); @@ -111,13 +75,8 @@ public: void AddStore(net::CookieStore *store); void OnCookieChanged(const net::CookieChangeInfo &change); - -private: - void GetAllCookiesCallbackOnUIThread(qint64 callbackId, const net::CookieList &cookies); - void SetCookieCallbackOnUIThread(qint64 callbackId, net::CanonicalCookie::CookieInclusionStatus status); - void DeleteCookiesCallbackOnUIThread(qint64 callbackId, uint numCookies); }; -} +} // namespace QtWebEngineCore #endif // COOKIE_MONSTER_DELEGATE_QT_H diff --git a/src/core/net/custom_url_loader_factory.cpp b/src/core/net/custom_url_loader_factory.cpp index 709e4451b..954253b54 100644 --- a/src/core/net/custom_url_loader_factory.cpp +++ b/src/core/net/custom_url_loader_factory.cpp @@ -1,49 +1,12 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "custom_url_loader_factory.h" #include "base/strings/stringprintf.h" -#include "base/task/post_task.h" +#include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/system/data_pipe.h" @@ -52,14 +15,20 @@ #include "net/http/http_status_code.h" #include "net/http/http_util.h" #include "services/network/public/cpp/cors/cors.h" +#include "services/network/public/cpp/resource_request.h" #include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "services/network/public/mojom/url_response_head.mojom.h" +#include "url/url_util.h" +#include "url/url_util_qt.h" #include "api/qwebengineurlscheme.h" #include "net/url_request_custom_job_proxy.h" #include "profile_adapter.h" +#include "qwebengineloadinginfo.h" #include "type_conversion.h" +#include "web_contents_adapter_client.h" +#include "web_contents_view_qt.h" #include <QtCore/qbytearray.h> #include <QtCore/qfile.h> @@ -67,6 +36,7 @@ #include <QtCore/qiodevice.h> #include <QtCore/qmimedatabase.h> #include <QtCore/qmimedata.h> +#include <QtCore/qpointer.h> #include <QtCore/qurl.h> namespace QtWebEngineCore { @@ -78,26 +48,28 @@ class CustomURLLoader : public network::mojom::URLLoader { public: static void CreateAndStart(const network::ResourceRequest &request, - network::mojom::URLLoaderRequest loader, - network::mojom::URLLoaderClientPtrInfo client_info, - QPointer<ProfileAdapter> profileAdapter) + mojo::PendingReceiver<network::mojom::URLLoader> loader, + mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote, + QPointer<ProfileAdapter> profileAdapter, + content::WebContents *webContents) { // CustomURLLoader will handle its own life-cycle, and delete when // the client lets go. - auto *customUrlLoader = new CustomURLLoader(request, std::move(loader), std::move(client_info), profileAdapter); + auto *customUrlLoader = new CustomURLLoader(request, std::move(loader), std::move(client_remote), profileAdapter, webContents); customUrlLoader->Start(); } // network::mojom::URLLoader: void FollowRedirect(const std::vector<std::string> &removed_headers, const net::HttpRequestHeaders &modified_headers, - const base::Optional<GURL> &new_url) override + const net::HttpRequestHeaders &modified_cors_exempt_headers, // FIXME: do something with this? + const absl::optional<GURL> &new_url) override { // We can be asked for follow our own redirect scoped_refptr<URLRequestCustomJobProxy> proxy = new URLRequestCustomJobProxy(this, m_proxy->m_scheme, m_proxy->m_profileAdapter); m_proxy->m_client = nullptr; // m_taskRunner->PostTask(FROM_HERE, base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy)); - base::PostTask(FROM_HERE, { content::BrowserThread::UI }, + content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy)); m_proxy = std::move(proxy); if (new_url) @@ -116,24 +88,27 @@ public: private: CustomURLLoader(const network::ResourceRequest &request, - network::mojom::URLLoaderRequest loader, - network::mojom::URLLoaderClientPtrInfo client_info, - QPointer<ProfileAdapter> profileAdapter) + mojo::PendingReceiver<network::mojom::URLLoader> loader, + mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote, + QPointer<ProfileAdapter> profileAdapter, + content::WebContents *webContents) // ### We can opt to run the url-loader on the UI thread instead - : m_taskRunner(base::CreateSingleThreadTaskRunner({ content::BrowserThread::IO })) + : m_taskRunner(content::GetIOThreadTaskRunner({})) , m_proxy(new URLRequestCustomJobProxy(this, request.url.scheme(), profileAdapter)) - , m_binding(this, std::move(loader)) - , m_client(std::move(client_info)) + , m_webContents(webContents) + , m_receiver(this, std::move(loader)) + , m_client(std::move(client_remote)) , m_request(request) { DCHECK(m_taskRunner->RunsTasksInCurrentSequence()); - m_binding.set_connection_error_handler( - base::BindOnce(&CustomURLLoader::OnConnectionError, m_weakPtrFactory.GetWeakPtr())); + m_receiver.set_disconnect_handler( + base::BindOnce(&CustomURLLoader::OnConnectionError, m_weakPtrFactory.GetWeakPtr())); m_firstBytePosition = 0; m_device = nullptr; m_error = 0; QWebEngineUrlScheme scheme = QWebEngineUrlScheme::schemeByName(QByteArray::fromStdString(request.url.scheme())); m_corsEnabled = scheme.flags().testFlag(QWebEngineUrlScheme::CorsEnabled); + m_isLocal = scheme.flags().testFlag(QWebEngineUrlScheme::LocalScheme); } ~CustomURLLoader() override = default; @@ -147,15 +122,28 @@ private: if (!m_request.request_initiator) return CompleteWithFailure(net::ERR_INVALID_ARGUMENT); - // Custom schemes are not covered by CorsURLLoader, so we need to reject CORS requests manually. - if (!m_corsEnabled && !m_request.request_initiator->IsSameOriginWith(url::Origin::Create(m_request.url))) - return CompleteWithFailure(network::CorsErrorStatus(network::mojom::CorsError::kCorsDisabledScheme)); + if (m_isLocal) { + std::string fromScheme = m_request.request_initiator->GetTupleOrPrecursorTupleIfOpaque().scheme(); + const std::vector<std::string> &localSchemes = url::GetLocalSchemes(); + bool fromLocal = base::Contains(localSchemes, fromScheme); + bool hasLocalAccess = fromLocal; + if (const url::CustomScheme *cs = url::CustomScheme::FindScheme(fromScheme)) + hasLocalAccess = cs->flags & (url::CustomScheme::LocalAccessAllowed | url::CustomScheme::Local); + if (!hasLocalAccess) + return CompleteWithFailure(net::ERR_ACCESS_DENIED); + } else if (!m_corsEnabled && !m_request.request_initiator->IsSameOriginWith(url::Origin::Create(m_request.url))) { + // Custom schemes are not covered by CorsURLLoader, so we need to reject CORS requests manually. + return CompleteWithFailure(network::CorsErrorStatus(network::mojom::CorsError::kCorsDisabledScheme)); + } } + if (mojo::CreateDataPipe(nullptr, m_pipeProducerHandle, m_pipeConsumerHandle) != MOJO_RESULT_OK) + return CompleteWithFailure(net::ERR_FAILED); + m_head = network::mojom::URLResponseHead::New(); m_head->request_start = base::TimeTicks::Now(); - if (!m_pipe.consumer_handle.is_valid()) + if (!m_pipeConsumerHandle.is_valid()) return CompleteWithFailure(net::ERR_FAILED); std::map<std::string, std::string> headers; @@ -170,9 +158,11 @@ private: m_firstBytePosition = m_byteRange.first_byte_position(); // m_taskRunner->PostTask(FROM_HERE, - base::PostTask(FROM_HERE, { content::BrowserThread::UI }, - base::BindOnce(&URLRequestCustomJobProxy::initialize, m_proxy, - m_request.url, m_request.method, m_request.request_initiator, std::move(headers))); + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce(&URLRequestCustomJobProxy::initialize, m_proxy, m_request.url, + m_request.method, m_request.request_initiator, std::move(headers), + m_request.request_body)); } void CompleteWithFailure(network::CorsErrorStatus cors_error) @@ -192,7 +182,7 @@ private: void OnConnectionError() { DCHECK(m_taskRunner->RunsTasksInCurrentSequence()); - m_binding.Close(); + m_receiver.reset(); if (m_client.is_bound()) ClearProxyAndClient(false); else @@ -223,9 +213,9 @@ private: m_device->close(); m_device = nullptr; // m_taskRunner->PostTask(FROM_HERE, base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy)); - base::PostTask(FROM_HERE, { content::BrowserThread::UI }, + content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, base::BindOnce(&URLRequestCustomJobProxy::release, m_proxy)); - if (!wait_for_loader_error || !m_binding.is_bound()) + if (!wait_for_loader_error || !m_receiver.is_bound()) delete this; } @@ -282,20 +272,26 @@ private: headers += "Access-Control-Allow-Credentials: true\n"; } } + for (auto it = m_additionalResponseHeaders.cbegin(); + it != m_additionalResponseHeaders.cend(); ++it) { + headers += it.key().toLower().toStdString() + ": " + it.value().toLower().toStdString() + + "\n"; + } m_head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders(headers)); m_head->encoded_data_length = m_head->headers->raw_headers().length(); if (!m_redirect.is_empty()) { - m_head->content_length = m_head->encoded_body_length = -1; - net::URLRequest::FirstPartyURLPolicy first_party_url_policy = - m_request.update_first_party_url_on_redirect ? net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT - : net::URLRequest::NEVER_CHANGE_FIRST_PARTY_URL; + m_head->content_length = {}; + m_head->encoded_body_length = {}; + net::RedirectInfo::FirstPartyURLPolicy first_party_url_policy = + m_request.update_first_party_url_on_redirect ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT + : net::RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL; net::RedirectInfo redirectInfo = net::RedirectInfo::ComputeRedirectInfo( m_request.method, m_request.url, m_request.site_for_cookies, first_party_url_policy, m_request.referrer_policy, m_request.referrer.spec(), net::HTTP_SEE_OTHER, - m_redirect, base::nullopt, false /*insecure_scheme_was_upgraded*/); + m_redirect, absl::nullopt, false /*insecure_scheme_was_upgraded*/); m_client->OnReceiveRedirect(redirectInfo, std::move(m_head)); m_head = nullptr; // ### should m_request be updated with RedirectInfo? (see FollowRedirect) @@ -305,19 +301,17 @@ private: m_head->mime_type = m_mimeType; m_head->charset = m_charset; m_headerBytesRead = m_head->headers->raw_headers().length(); - m_client->OnReceiveResponse(std::move(m_head)); - m_client->OnStartLoadingResponseBody(std::move(m_pipe.consumer_handle)); + m_client->OnReceiveResponse(std::move(m_head), std::move(m_pipeConsumerHandle), absl::nullopt); m_head = nullptr; - if (readAvailableData()) // May delete this - return; - m_watcher = std::make_unique<mojo::SimpleWatcher>( - FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC, m_taskRunner); - m_watcher->Watch(m_pipe.producer_handle.get(), MOJO_HANDLE_SIGNAL_WRITABLE, + FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, m_taskRunner); + m_watcher->Watch(m_pipeProducerHandle.get(), MOJO_HANDLE_SIGNAL_WRITABLE, MOJO_WATCH_CONDITION_SATISFIED, base::BindRepeating(&CustomURLLoader::notifyReadyWrite, m_weakPtrFactory.GetWeakPtr())); + + readAvailableData(); // May delete this } void notifyCanceled() override { @@ -356,10 +350,20 @@ private: } m_head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders(headers)); m_head->encoded_data_length = m_head->headers->raw_headers().length(); - m_head->content_length = m_head->encoded_body_length = -1; - m_client->OnReceiveResponse(std::move(m_head)); + m_head->content_length = {}; + m_head->encoded_body_length = {}; + m_client->OnReceiveResponse(std::move(m_head), mojo::ScopedDataPipeConsumerHandle(), absl::nullopt); CompleteWithFailure(net::Error(error)); } + void notifySuccess() override + { + if (m_webContents) { + WebContentsAdapterClient *client = WebContentsViewQt::from(static_cast<content::WebContentsImpl *>(m_webContents)->GetView())->client(); + QWebEngineLoadingInfo info(toQt(m_request.url), QWebEngineLoadingInfo::LoadSucceededStatus); + client->loadFinished(std::move(info)); + client->updateNavigationActions(); + } + } void notifyReadyRead() override { DCHECK(m_taskRunner->RunsTasksInCurrentSequence()); @@ -383,10 +387,12 @@ private: void *buffer = nullptr; uint32_t bufferSize = 0; - MojoResult beginResult = m_pipe.producer_handle->BeginWriteData( + MojoResult beginResult = m_pipeProducerHandle->BeginWriteData( &buffer, &bufferSize, MOJO_BEGIN_WRITE_DATA_FLAG_NONE); - if (beginResult == MOJO_RESULT_SHOULD_WAIT) + if (beginResult == MOJO_RESULT_SHOULD_WAIT) { + m_watcher->ArmOrNotify(); return false; // Wait for pipe watcher + } if (beginResult != MOJO_RESULT_OK) break; if (m_maxBytesToRead > 0 && m_maxBytesToRead <= int64_t{std::numeric_limits<uint32_t>::max()}) @@ -394,17 +400,24 @@ private: int readResult = m_device->read(static_cast<char *>(buffer), bufferSize); uint32_t bytesRead = std::max(readResult, 0); - m_pipe.producer_handle->EndWriteData(bytesRead); + m_pipeProducerHandle->EndWriteData(bytesRead); m_totalBytesRead += bytesRead; m_client->OnTransferSizeUpdated(m_totalBytesRead); - if (m_device->atEnd() || (m_maxBytesToRead > 0 && m_totalBytesRead >= m_maxBytesToRead)) { + const bool deviceAtEnd = m_device->atEnd(); + if ((deviceAtEnd && !m_device->isSequential()) + || (m_maxBytesToRead > 0 && m_totalBytesRead >= m_maxBytesToRead)) { OnTransferComplete(MOJO_RESULT_OK); return true; // Done with reading } if (readResult == 0) return false; // Wait for readyRead + if (readResult < 0 && deviceAtEnd && m_device->isSequential()) { + // Failure on read, and sequential device claiming to be at end, so treat it as a successful end-of-data. + OnTransferComplete(MOJO_RESULT_OK); + return true; // Done with reading + } if (readResult < 0) break; } @@ -435,10 +448,12 @@ private: scoped_refptr<base::SequencedTaskRunner> m_taskRunner; scoped_refptr<URLRequestCustomJobProxy> m_proxy; + content::WebContents *m_webContents; - mojo::Binding<network::mojom::URLLoader> m_binding; - network::mojom::URLLoaderClientPtr m_client; - mojo::DataPipe m_pipe; + mojo::Receiver<network::mojom::URLLoader> m_receiver; + mojo::Remote<network::mojom::URLLoaderClient> m_client; + mojo::ScopedDataPipeProducerHandle m_pipeProducerHandle; + mojo::ScopedDataPipeConsumerHandle m_pipeConsumerHandle; std::unique_ptr<mojo::SimpleWatcher> m_watcher; net::HttpByteRange m_byteRange; @@ -449,24 +464,26 @@ private: qint64 m_headerBytesRead = 0; qint64 m_totalBytesRead = 0; bool m_corsEnabled; + bool m_isLocal; base::WeakPtrFactory<CustomURLLoader> m_weakPtrFactory{this}; - - DISALLOW_COPY_AND_ASSIGN(CustomURLLoader); }; class CustomURLLoaderFactory : public network::mojom::URLLoaderFactory { public: - CustomURLLoaderFactory(ProfileAdapter *profileAdapter) - : m_taskRunner(base::CreateSequencedTaskRunner({ content::BrowserThread::IO })) + CustomURLLoaderFactory(ProfileAdapter *profileAdapter, content::WebContents *webContents, mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) + : m_taskRunner(content::GetIOThreadTaskRunner({})) , m_profileAdapter(profileAdapter) + , m_webContents(webContents) { + m_receivers.set_disconnect_handler(base::BindRepeating( + &CustomURLLoaderFactory::OnDisconnect, base::Unretained(this))); + m_receivers.Add(this, std::move(receiver)); } ~CustomURLLoaderFactory() override = default; // network::mojom::URLLoaderFactory: void CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader, - int32_t routing_id, int32_t request_id, uint32_t options, const network::ResourceRequest &request, @@ -474,7 +491,6 @@ public: const net::MutableNetworkTrafficAnnotationTag &traffic_annotation) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - Q_UNUSED(routing_id); Q_UNUSED(request_id); Q_UNUSED(options); Q_UNUSED(traffic_annotation); @@ -482,7 +498,7 @@ public: m_taskRunner->PostTask(FROM_HERE, base::BindOnce(&CustomURLLoader::CreateAndStart, request, std::move(loader), std::move(client), - m_profileAdapter)); + m_profileAdapter, m_webContents)); } @@ -491,17 +507,30 @@ public: m_receivers.Add(this, std::move(receiver)); } + void OnDisconnect() + { + if (m_receivers.empty()) + delete this; + } + + static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create(ProfileAdapter *profileAdapter, content::WebContents *webContents) + { + mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote; + new CustomURLLoaderFactory(profileAdapter, webContents, pending_remote.InitWithNewPipeAndPassReceiver()); + return pending_remote; + } + const scoped_refptr<base::SequencedTaskRunner> m_taskRunner; mojo::ReceiverSet<network::mojom::URLLoaderFactory> m_receivers; QPointer<ProfileAdapter> m_profileAdapter; - DISALLOW_COPY_AND_ASSIGN(CustomURLLoaderFactory); + content::WebContents *m_webContents; }; } // namespace -std::unique_ptr<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter) +mojo::PendingRemote<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter, content::WebContents *webContents) { - return std::make_unique<CustomURLLoaderFactory>(profileAdapter); + return CustomURLLoaderFactory::Create(profileAdapter, webContents); } } // namespace QtWebEngineCore diff --git a/src/core/net/custom_url_loader_factory.h b/src/core/net/custom_url_loader_factory.h index 58adf4b79..e4a767c85 100644 --- a/src/core/net/custom_url_loader_factory.h +++ b/src/core/net/custom_url_loader_factory.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // // W A R N I N G @@ -51,8 +15,11 @@ #ifndef CUSTOM_URL_LOADER_FACTORY_H_ #define CUSTOM_URL_LOADER_FACTORY_H_ -#include <memory> +#include "mojo/public/cpp/bindings/pending_remote.h" +namespace content { +class WebContents; +} namespace network { namespace mojom { class URLLoaderFactory; @@ -62,7 +29,7 @@ class URLLoaderFactory; namespace QtWebEngineCore { class ProfileAdapter; -std::unique_ptr<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter); +mojo::PendingRemote<network::mojom::URLLoaderFactory> CreateCustomURLLoaderFactory(ProfileAdapter *profileAdapter, content::WebContents *webContents); } // namespace QtWebEngineCore diff --git a/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp b/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp index f6bddd7b2..159fa28ca 100644 --- a/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp +++ b/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp @@ -1,136 +1,201 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// based on chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.cc +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. #include "plugin_response_interceptor_url_loader_throttle.h" -#include "base/bind.h" -#include "base/task/post_task.h" -#include "content/public/browser/browser_task_traits.h" +#include "base/functional/bind.h" +#include "base/uuid.h" +#include "chrome/browser/extensions/api/streams_private/streams_private_api.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/download_utils.h" +#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" +#include "extensions/common/manifest_handlers/mime_types_handler.h" +#include "third_party/blink/public/mojom/loader/transferrable_url_loader.mojom.h" #include "extensions/extension_system_qt.h" -#include "profile_adapter.h" -#include "profile_io_data_qt.h" -#include "profile_qt.h" #include "web_contents_delegate_qt.h" +#include "web_engine_settings.h" #include <string> +#include <tuple> -namespace QtWebEngineCore { - -void onPdfStreamIntercepted(const GURL &original_url, std::string extension_id, int frame_tree_node_id) +namespace { +void ClearAllButFrameAncestors(network::mojom::URLResponseHead *response_head) { - content::WebContents *web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); - if (!web_contents) - return; + response_head->headers->RemoveHeader("Content-Security-Policy"); + response_head->headers->RemoveHeader("Content-Security-Policy-Report-Only"); - WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate()); - if (!contentsDelegate) + if (!response_head->parsed_headers) return; - WebEngineSettings *settings = contentsDelegate->webEngineSettings(); - if (!settings->testAttribute(QWebEngineSettings::PdfViewerEnabled) - || !settings->testAttribute(QWebEngineSettings::PluginsEnabled)) { - // If the applications has been set up to always download PDF files to open them in an - // external viewer, trigger the download. - std::unique_ptr<download::DownloadUrlParameters> params( - content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(web_contents, original_url, - MISSING_TRAFFIC_ANNOTATION)); - content::BrowserContext::GetDownloadManager(web_contents->GetBrowserContext())->DownloadUrl(std::move(params)); - return; + std::vector<network::mojom::ContentSecurityPolicyPtr> &csp = + response_head->parsed_headers->content_security_policy; + std::vector<network::mojom::ContentSecurityPolicyPtr> cleared; + + for (auto &policy : csp) { + auto frame_ancestors = policy->directives.find(network::mojom::CSPDirectiveName::FrameAncestors); + if (frame_ancestors == policy->directives.end()) + continue; + + auto cleared_policy = network::mojom::ContentSecurityPolicy::New(); + cleared_policy->self_origin = std::move(policy->self_origin); + cleared_policy->header = std::move(policy->header); + cleared_policy->header->header_value = ""; + cleared_policy->directives[network::mojom::CSPDirectiveName::FrameAncestors] = std::move(frame_ancestors->second); + + auto raw_frame_ancestors = policy->raw_directives.find(network::mojom::CSPDirectiveName::FrameAncestors); + DCHECK(raw_frame_ancestors != policy->raw_directives.end()); + + cleared_policy->header->header_value = "frame-ancestors " + raw_frame_ancestors->second; + response_head->headers->AddHeader( + cleared_policy->header->type == network::mojom::ContentSecurityPolicyType::kEnforce + ? "Content-Security-Policy" + : "Content-Security-Policy-Report-Only", + cleared_policy->header->header_value); + cleared_policy->raw_directives[network::mojom::CSPDirectiveName::FrameAncestors] = + std::move(raw_frame_ancestors->second); + + cleared.push_back(std::move(cleared_policy)); } - // The URL passes the original pdf resource url, that will be requested - // by the pdf viewer extension page. - content::NavigationController::LoadURLParams params( - GURL(base::StringPrintf("%s://%s/index.html?%s", extensions::kExtensionScheme, - extension_id.c_str(), original_url.spec().c_str()))); - - params.frame_tree_node_id = frame_tree_node_id; - web_contents->GetController().LoadURLWithParams(params); + csp.swap(cleared); } +} // namespace -PluginResponseInterceptorURLLoaderThrottle::PluginResponseInterceptorURLLoaderThrottle( - content::ResourceContext *resource_context, int resource_type, int frame_tree_node_id) - : m_resource_context(resource_context), m_resource_type(resource_type), m_frame_tree_node_id(frame_tree_node_id) -{} +namespace QtWebEngineCore { PluginResponseInterceptorURLLoaderThrottle::PluginResponseInterceptorURLLoaderThrottle( - content::BrowserContext *browser_context, int resource_type, int frame_tree_node_id) - : m_browser_context(browser_context), m_resource_type(resource_type), m_frame_tree_node_id(frame_tree_node_id) + network::mojom::RequestDestination request_destination, + int frame_tree_node_id) + : m_request_destination(request_destination), m_frame_tree_node_id(frame_tree_node_id) {} void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL &response_url, network::mojom::URLResponseHead *response_head, bool *defer) { - Q_UNUSED(defer); - if (content::download_utils::MustDownload(response_url, response_head->headers.get(), response_head->mime_type)) + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + content::WebContents *web_contents = content::WebContents::FromFrameTreeNodeId(m_frame_tree_node_id); + if (!web_contents) return; - if (m_resource_context) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - } else { - DCHECK(m_browser_context); - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - } + if (content::download_utils::MustDownload( + web_contents->GetBrowserContext(), + response_url, response_head->headers.get(), response_head->mime_type)) + return; std::string extension_id; - // FIXME: We should use extensions::InfoMap in the future: if (response_head->mime_type == "application/pdf") extension_id = extension_misc::kPdfExtensionId; if (extension_id.empty()) return; - *defer = true; + WebContentsDelegateQt *contentsDelegate = static_cast<WebContentsDelegateQt *>(web_contents->GetDelegate()); + if (!contentsDelegate) + return; + + WebEngineSettings *settings = contentsDelegate->webEngineSettings(); + if (!settings->testAttribute(QWebEngineSettings::PdfViewerEnabled) + || !settings->testAttribute(QWebEngineSettings::PluginsEnabled)) { + // PluginServiceFilterQt will inform the URLLoader about the disabled state of plugins + // and we can expect the download to be triggered automatically. It's unnecessary to + // go further and start the guest view embedding process. + return; + } + + // Chrome's PDF Extension does not work properly in the face of a restrictive + // Content-Security-Policy, and does not currently respect the policy anyway. + // Ignore CSP served on a PDF response. https://crbug.com/271452 + if (extension_id == extension_misc::kPdfExtensionId && response_head->headers) + ClearAllButFrameAncestors(response_head); + + MimeTypesHandler::ReportUsedHandler(extension_id); + + std::string view_id = base::Uuid::GenerateRandomV4().AsLowercaseString(); + // The string passed down to the original client with the response body. + std::string payload = view_id; + + mojo::PendingRemote<network::mojom::URLLoader> dummy_new_loader; + std::ignore = dummy_new_loader.InitWithNewPipeAndPassReceiver(); + mojo::Remote<network::mojom::URLLoaderClient> new_client; + mojo::PendingReceiver<network::mojom::URLLoaderClient> new_client_receiver = + new_client.BindNewPipeAndPassReceiver(); + + + uint32_t data_pipe_size = 64U; + // Provide the MimeHandlerView code a chance to override the payload. This is + // the case where the resource is handled by frame-based MimeHandlerView. + *defer = extensions::MimeHandlerViewAttachHelper::OverrideBodyForInterceptedResponse( + m_frame_tree_node_id, response_url, response_head->mime_type, view_id, + &payload, &data_pipe_size, + base::BindOnce( + &PluginResponseInterceptorURLLoaderThrottle::ResumeLoad, + weak_factory_.GetWeakPtr())); + + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(data_pipe_size, producer_handle, consumer_handle)); + + uint32_t len = static_cast<uint32_t>(payload.size()); + CHECK_EQ(MOJO_RESULT_OK, + producer_handle->WriteData( + payload.c_str(), &len, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); + + network::URLLoaderCompletionStatus status(net::OK); + status.decoded_body_length = len; + new_client->OnComplete(status); + + mojo::PendingRemote<network::mojom::URLLoader> original_loader; + mojo::PendingReceiver<network::mojom::URLLoaderClient> original_client; + mojo::ScopedDataPipeConsumerHandle body = std::move(consumer_handle); + delegate_->InterceptResponse(std::move(dummy_new_loader), + std::move(new_client_receiver), + &original_loader, &original_client, + &body); + + // Make a deep copy of URLResponseHead before passing it cross-thread. + auto deep_copied_response = response_head->Clone(); + if (response_head->headers) { + deep_copied_response->headers = + base::MakeRefCounted<net::HttpResponseHeaders>( + response_head->headers->raw_headers()); + } + + auto transferrable_loader = blink::mojom::TransferrableURLLoader::New(); + transferrable_loader->url = GURL( + extensions::Extension::GetBaseURLFromExtensionId(extension_id).spec() + + base::Uuid::GenerateRandomV4().AsLowercaseString()); + transferrable_loader->url_loader = std::move(original_loader); + transferrable_loader->url_loader_client = std::move(original_client); + transferrable_loader->head = std::move(deep_copied_response); + transferrable_loader->head->intercepted_by_plugin = true; + transferrable_loader->body = std::move(body); + + bool embedded = m_request_destination != + network::mojom::RequestDestination::kDocument; + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce( + &extensions::StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent, + extension_id, view_id, embedded, m_frame_tree_node_id, + std::move(transferrable_loader), response_url)); +} - base::PostTask(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&onPdfStreamIntercepted, - response_url, - extension_id, - m_frame_tree_node_id)); +void PluginResponseInterceptorURLLoaderThrottle::ResumeLoad() +{ + delegate_->Resume(); } } // namespace QtWebEngineCore diff --git a/src/core/net/plugin_response_interceptor_url_loader_throttle.h b/src/core/net/plugin_response_interceptor_url_loader_throttle.h index 7b9db6490..fb3918c45 100644 --- a/src/core/net/plugin_response_interceptor_url_loader_throttle.h +++ b/src/core/net/plugin_response_interceptor_url_loader_throttle.h @@ -1,51 +1,15 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef PLUGIN_RESPONSE_INTERCEPTOR_URL_LOADER_THROTTLE_H_ #define PLUGIN_RESPONSE_INTERCEPTOR_URL_LOADER_THROTTLE_H_ -#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "services/network/public/mojom/fetch_api.mojom-shared.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" namespace content { class BrowserContext; -class ResourceContext; } namespace QtWebEngineCore { @@ -53,22 +17,23 @@ namespace QtWebEngineCore { class PluginResponseInterceptorURLLoaderThrottle : public blink::URLLoaderThrottle { public: - PluginResponseInterceptorURLLoaderThrottle(content::ResourceContext *resource_context, - int resource_type, int frame_tree_node_id); - PluginResponseInterceptorURLLoaderThrottle(content::BrowserContext *browser_context, - int resource_type, int frame_tree_node_id); + PluginResponseInterceptorURLLoaderThrottle(network::mojom::RequestDestination request_destination, + int frame_tree_node_id); ~PluginResponseInterceptorURLLoaderThrottle() override = default; private: // content::URLLoaderThrottle overrides; void WillProcessResponse(const GURL &response_url, network::mojom::URLResponseHead *response_head, bool *defer) override; - content::ResourceContext *m_resource_context = nullptr; - content::BrowserContext *m_browser_context = nullptr; - const int m_resource_type; + // Resumes loading for an intercepted response. This would give the extension + // layer chance to initialize its browser side state. + void ResumeLoad(); + + const network::mojom::RequestDestination m_request_destination; const int m_frame_tree_node_id; - DISALLOW_COPY_AND_ASSIGN(PluginResponseInterceptorURLLoaderThrottle); + base::WeakPtrFactory<PluginResponseInterceptorURLLoaderThrottle> + weak_factory_{this}; }; } // namespace QtWebEngineCore diff --git a/src/core/net/proxy_config_monitor.cpp b/src/core/net/proxy_config_monitor.cpp index a0aaf0c05..8315b7bf2 100644 --- a/src/core/net/proxy_config_monitor.cpp +++ b/src/core/net/proxy_config_monitor.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // originally based on chrome/browser/net/proxy_config_monitor.cc // Copyright 2017 The Chromium Authors. All rights reserved. @@ -46,15 +10,11 @@ #include "proxy_config_monitor.h" #include "proxy_config_service_qt.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task/post_task.h" -#include "build/build_config.h" -#include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "content/public/browser/browser_task_traits.h" +#include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/associated_interface_ptr.h" #include "mojo/public/cpp/bindings/pending_remote.h" -#include "net/proxy_resolution/proxy_resolution_service.h" +#include "net/proxy_resolution/proxy_config_with_annotation.h" #include "services/network/public/mojom/network_context.mojom.h" #include <utility> @@ -65,9 +25,7 @@ ProxyConfigMonitor::ProxyConfigMonitor(PrefService *prefs) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - proxy_config_service_.reset( - new ProxyConfigServiceQt( - prefs, base::CreateSingleThreadTaskRunner({ BrowserThread::UI }))); + proxy_config_service_.reset(new ProxyConfigServiceQt(prefs, content::GetUIThreadTaskRunner({}))); proxy_config_service_->AddObserver(this); } diff --git a/src/core/net/proxy_config_monitor.h b/src/core/net/proxy_config_monitor.h index fda6a6fb9..585e4b7ed 100644 --- a/src/core/net/proxy_config_monitor.h +++ b/src/core/net/proxy_config_monitor.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // originally based on chrome/browser/net/proxy_config_monitor.h // Copyright 2017 The Chromium Authors. All rights reserved. @@ -46,17 +10,11 @@ #define PROXY_CONFIG_MONITOR_H #include <memory> -#include <string> -#include "base/macros.h" -#include "build/buildflag.h" -#include "extensions/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote_set.h" #include "net/proxy_resolution/proxy_config_service.h" #include "services/network/public/mojom/network_context.mojom-forward.h" -#include "services/network/public/mojom/network_service.mojom-forward.h" -#include "services/network/public/mojom/proxy_config.mojom-forward.h" #include "services/network/public/mojom/proxy_config_with_annotation.mojom.h" namespace net { @@ -96,8 +54,6 @@ private: mojo::ReceiverSet<network::mojom::ProxyConfigPollerClient> poller_receiver_set_; mojo::RemoteSet<network::mojom::ProxyConfigClient> proxy_config_client_set_; - - DISALLOW_COPY_AND_ASSIGN(ProxyConfigMonitor); }; -#endif // !PROXY_CONFIG_MONITOR_H +#endif // PROXY_CONFIG_MONITOR_H diff --git a/src/core/net/proxy_config_service_qt.cpp b/src/core/net/proxy_config_service_qt.cpp index bc934c960..fcce08550 100644 --- a/src/core/net/proxy_config_service_qt.cpp +++ b/src/core/net/proxy_config_service_qt.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only //================ Based on ChromeProxyConfigService ======================= @@ -45,23 +9,22 @@ #include "proxy_config_service_qt.h" -#include "base/bind.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" -#include "content/public/browser/browser_thread.h" -#include "net/proxy_resolution/configured_proxy_resolution_service.h" +#include "net/base/proxy_server.h" -using content::BrowserThread; +#include <QNetworkProxy> net::ProxyServer ProxyConfigServiceQt::fromQNetworkProxy(const QNetworkProxy &qtProxy) { - net::HostPortPair hostPortPair(qtProxy.hostName().toStdString(), qtProxy.port()); + std::string host = qtProxy.hostName().toStdString(); + uint16_t port = qtProxy.port(); switch (qtProxy.type()) { case QNetworkProxy::Socks5Proxy: - return net::ProxyServer(net::ProxyServer::SCHEME_SOCKS5, hostPortPair); + return net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_SOCKS5, host, port); case QNetworkProxy::HttpProxy: case QNetworkProxy::HttpCachingProxy: case QNetworkProxy::FtpCachingProxy: - return net::ProxyServer(net::ProxyServer::SCHEME_HTTP, hostPortPair); + return net::ProxyServer::FromSchemeHostAndPort(net::ProxyServer::SCHEME_HTTP, host, port); case QNetworkProxy::NoProxy: case QNetworkProxy::DefaultProxy: return net::ProxyServer(net::ProxyServer::SCHEME_DIRECT, net::HostPortPair()); @@ -71,8 +34,8 @@ net::ProxyServer ProxyConfigServiceQt::fromQNetworkProxy(const QNetworkProxy &qt } ProxyConfigServiceQt::ProxyConfigServiceQt(PrefService *prefService, - const scoped_refptr<base::SingleThreadTaskRunner> &taskRunner) - : m_baseService(net::ConfiguredProxyResolutionService::CreateSystemProxyConfigService(taskRunner)) + const scoped_refptr<base::SequencedTaskRunner> &taskRunner) + : m_baseService(net::ProxyConfigService::CreateSystemProxyConfigService(taskRunner)) , m_usesSystemConfiguration(false) , m_registeredObserver(false) , m_prefState(prefService diff --git a/src/core/net/proxy_config_service_qt.h b/src/core/net/proxy_config_service_qt.h index c0928bc03..49c9877a5 100644 --- a/src/core/net/proxy_config_service_qt.h +++ b/src/core/net/proxy_config_service_qt.h @@ -1,49 +1,11 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef PROXY_CONFIG_SERVICE_QT_H #define PROXY_CONFIG_SERVICE_QT_H -#include "base/memory/ref_counted.h" #include "base/observer_list.h" -#include "base/single_thread_task_runner.h" - +#include "base/task/sequenced_task_runner.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_config_service.h" #include "net/proxy_resolution/proxy_config_with_annotation.h" @@ -61,7 +23,7 @@ public: static net::ProxyServer fromQNetworkProxy(const QNetworkProxy &); explicit ProxyConfigServiceQt(PrefService *prefService, - const scoped_refptr<base::SingleThreadTaskRunner> &taskRunner); + const scoped_refptr<base::SequencedTaskRunner> &taskRunner); ~ProxyConfigServiceQt() override; // ProxyConfigService implementation: @@ -97,8 +59,6 @@ private: ProxyPrefs::ConfigState m_prefState; SEQUENCE_CHECKER(m_sequenceChecker); - - DISALLOW_COPY_AND_ASSIGN(ProxyConfigServiceQt); }; #endif // PROXY_CONFIG_SERVICE_QT_H diff --git a/src/core/net/proxying_restricted_cookie_manager_qt.cpp b/src/core/net/proxying_restricted_cookie_manager_qt.cpp index b0b46c817..d4d5cc4ab 100644 --- a/src/core/net/proxying_restricted_cookie_manager_qt.cpp +++ b/src/core/net/proxying_restricted_cookie_manager_qt.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // originally based on android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc: // Copyright 2019 The Chromium Authors. All rights reserved. @@ -46,12 +10,10 @@ #include "api/qwebenginecookiestore.h" #include "api/qwebenginecookiestore_p.h" -#include "profile_adapter.h" -#include "profile_qt.h" +#include "profile_io_data_qt.h" #include "type_conversion.h" #include "base/memory/ptr_util.h" -#include "base/task/post_task.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" @@ -61,18 +23,14 @@ namespace QtWebEngineCore { // static void ProxyingRestrictedCookieManagerQt::CreateAndBind(ProfileIODataQt *profileIoData, mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm, - bool is_service_worker, - int process_id, - int frame_id, mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + content::GetIOThreadTaskRunner({})->PostTask(FROM_HERE, base::BindOnce(&ProxyingRestrictedCookieManagerQt::CreateAndBindOnIoThread, profileIoData, std::move(underlying_rcm), - is_service_worker, process_id, frame_id, std::move(receiver))); } @@ -80,31 +38,21 @@ void ProxyingRestrictedCookieManagerQt::CreateAndBind(ProfileIODataQt *profileIo // static void ProxyingRestrictedCookieManagerQt::CreateAndBindOnIoThread(ProfileIODataQt *profileIoData, mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm, - bool is_service_worker, - int process_id, - int frame_id, mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); auto wrapper = base::WrapUnique(new ProxyingRestrictedCookieManagerQt( profileIoData->getWeakPtrOnIOThread(), - std::move(underlying_rcm), - is_service_worker, process_id, frame_id)); + std::move(underlying_rcm))); mojo::MakeSelfOwnedReceiver(std::move(wrapper), std::move(receiver)); } ProxyingRestrictedCookieManagerQt::ProxyingRestrictedCookieManagerQt( base::WeakPtr<ProfileIODataQt> profileIoData, - mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlyingRestrictedCookieManager, - bool is_service_worker, - int32_t process_id, - int32_t frame_id) + mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlyingRestrictedCookieManager) : m_profileIoData(std::move(profileIoData)) , underlying_restricted_cookie_manager_(std::move(underlyingRestrictedCookieManager)) - , is_service_worker_(is_service_worker) - , process_id_(process_id) - , frame_id_(frame_id) , weak_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); @@ -117,16 +65,17 @@ ProxyingRestrictedCookieManagerQt::~ProxyingRestrictedCookieManagerQt() void ProxyingRestrictedCookieManagerQt::GetAllForUrl(const GURL &url, const net::SiteForCookies &site_for_cookies, - const url::Origin &top_frame_origin, + const url::Origin &top_frame_origin, bool has_storage_access, network::mojom::CookieManagerGetOptionsPtr options, GetAllForUrlCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (allowCookies(url, site_for_cookies)) { - underlying_restricted_cookie_manager_->GetAllForUrl(url, site_for_cookies, top_frame_origin, std::move(options), std::move(callback)); + underlying_restricted_cookie_manager_->GetAllForUrl(url, site_for_cookies, top_frame_origin, has_storage_access, + std::move(options), std::move(callback)); } else { - std::move(callback).Run(std::vector<net::CanonicalCookie>()); + std::move(callback).Run(std::vector<net::CookieWithAccessResult>()); } } @@ -134,12 +83,15 @@ void ProxyingRestrictedCookieManagerQt::SetCanonicalCookie(const net::CanonicalC const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, + net::CookieInclusionStatus status, SetCanonicalCookieCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (allowCookies(url, site_for_cookies)) { - underlying_restricted_cookie_manager_->SetCanonicalCookie(cookie, url, site_for_cookies, top_frame_origin, std::move(callback)); + underlying_restricted_cookie_manager_->SetCanonicalCookie(cookie, url, site_for_cookies, top_frame_origin, + has_storage_access, status, std::move(callback)); } else { std::move(callback).Run(false); } @@ -148,45 +100,52 @@ void ProxyingRestrictedCookieManagerQt::SetCanonicalCookie(const net::CanonicalC void ProxyingRestrictedCookieManagerQt::AddChangeListener(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, mojo::PendingRemote<network::mojom::CookieChangeListener> listener, AddChangeListenerCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - underlying_restricted_cookie_manager_->AddChangeListener(url, site_for_cookies, top_frame_origin, std::move(listener), std::move(callback)); + underlying_restricted_cookie_manager_->AddChangeListener(url, site_for_cookies, top_frame_origin, has_storage_access, + std::move(listener), std::move(callback)); } void ProxyingRestrictedCookieManagerQt::SetCookieFromString(const GURL &url, const net::SiteForCookies &site_for_cookies, - const url::Origin &top_frame_origin, + const url::Origin &top_frame_origin, bool has_storage_access, const std::string &cookie, SetCookieFromStringCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (allowCookies(url, site_for_cookies)) { - underlying_restricted_cookie_manager_->SetCookieFromString(url, site_for_cookies, top_frame_origin, cookie, std::move(callback)); + underlying_restricted_cookie_manager_->SetCookieFromString(url, site_for_cookies, top_frame_origin, has_storage_access, + cookie, std::move(callback)); } else { - std::move(callback).Run(); + std::move(callback).Run(false, false); // FIXME: is true, true in aw_proxying_restricted_cookie_manager.cc though.. } } void ProxyingRestrictedCookieManagerQt::GetCookiesString(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, bool get_version_shared_memory, GetCookiesStringCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (allowCookies(url, site_for_cookies)) { - underlying_restricted_cookie_manager_->GetCookiesString(url, site_for_cookies, top_frame_origin, std::move(callback)); + underlying_restricted_cookie_manager_->GetCookiesString(url, site_for_cookies, top_frame_origin, + has_storage_access, get_version_shared_memory, + std::move(callback)); } else { - std::move(callback).Run(""); + std::move(callback).Run(network::mojom::kInvalidCookieVersion, base::ReadOnlySharedMemoryRegion(), ""); } } void ProxyingRestrictedCookieManagerQt::CookiesEnabledFor(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin & /*top_frame_origin*/, + bool /*has_storage_access*/, CookiesEnabledForCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); @@ -197,7 +156,7 @@ bool ProxyingRestrictedCookieManagerQt::allowCookies(const GURL &url, const net: { if (!m_profileIoData) return false; - return m_profileIoData->canGetCookies(toQt(site_for_cookies.RepresentativeUrl()), toQt(url)); + return m_profileIoData->canGetCookies(toQt(site_for_cookies.first_party_url()), toQt(url)); } } // namespace QtWebEngineCore diff --git a/src/core/net/proxying_restricted_cookie_manager_qt.h b/src/core/net/proxying_restricted_cookie_manager_qt.h index 3d4765b3b..faf0545c3 100644 --- a/src/core/net/proxying_restricted_cookie_manager_qt.h +++ b/src/core/net/proxying_restricted_cookie_manager_qt.h @@ -1,46 +1,9 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef PROXYING_RESTRICTED_COOKIE_MANAGER_QT_H #define PROXYING_RESTRICTED_COOKIE_MANAGER_QT_H -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/network/public/mojom/restricted_cookie_manager.mojom.h" @@ -56,9 +19,6 @@ public: // Expects to be called on the UI thread. static void CreateAndBind(ProfileIODataQt *profileIoData, mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm, - bool is_service_worker, - int process_id, - int frame_id, mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver); ~ProxyingRestrictedCookieManagerQt() override; @@ -67,30 +27,38 @@ public: void GetAllForUrl(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, network::mojom::CookieManagerGetOptionsPtr options, GetAllForUrlCallback callback) override; + void SetCanonicalCookie(const net::CanonicalCookie& cookie, const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, + net::CookieInclusionStatus status, SetCanonicalCookieCallback callback) override; void AddChangeListener(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, mojo::PendingRemote<network::mojom::CookieChangeListener> listener, AddChangeListenerCallback callback) override; void SetCookieFromString(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, const std::string &cookie, SetCookieFromStringCallback callback) override; void GetCookiesString(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, bool get_version_shared_memory, GetCookiesStringCallback callback) override; void CookiesEnabledFor(const GURL &url, const net::SiteForCookies &site_for_cookies, const url::Origin &top_frame_origin, + bool has_storage_access, CookiesEnabledForCallback callback) override; // Internal: @@ -98,28 +66,17 @@ public: private: ProxyingRestrictedCookieManagerQt(base::WeakPtr<ProfileIODataQt> profileIoData, - mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm, - bool is_service_worker, - int32_t process_id, - int32_t frame_id); + mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm); static void CreateAndBindOnIoThread(ProfileIODataQt *profileIoData, mojo::PendingRemote<network::mojom::RestrictedCookieManager> underlying_rcm, - bool is_service_worker, - int process_id, - int frame_id, mojo::PendingReceiver<network::mojom::RestrictedCookieManager> receiver); base::WeakPtr<ProfileIODataQt> m_profileIoData; mojo::Remote<network::mojom::RestrictedCookieManager> underlying_restricted_cookie_manager_; - bool is_service_worker_; - int process_id_; - int frame_id_; base::WeakPtrFactory<ProxyingRestrictedCookieManagerQt> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(ProxyingRestrictedCookieManagerQt); }; } // namespace QtWebEngineCore diff --git a/src/core/net/proxying_url_loader_factory_qt.cpp b/src/core/net/proxying_url_loader_factory_qt.cpp index d63659d2d..3a83ed7ea 100644 --- a/src/core/net/proxying_url_loader_factory_qt.cpp +++ b/src/core/net/proxying_url_loader_factory_qt.cpp @@ -1,75 +1,48 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "proxying_url_loader_factory_qt.h" #include <utility> -#include "base/bind.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" -#include "base/task/post_task.h" +#include "base/functional/bind.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/global_request_id.h" -#include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/content_constants.h" -#include "content/public/common/url_utils.h" -#include "net/base/load_flags.h" +#include "content/public/common/content_switches.h" +#include "net/base/filename_util.h" #include "net/http/http_status_code.h" -#include "net/http/http_util.h" +#include "services/network/public/cpp/cors/cors.h" +#include "services/network/public/cpp/resource_request.h" +#include "services/network/public/mojom/early_hints.mojom.h" +#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h" +#include "url/url_util.h" +#include "url/url_util_qt.h" #include "api/qwebengineurlrequestinfo_p.h" -#include "profile_qt.h" #include "type_conversion.h" +#include "web_contents_adapter.h" #include "web_contents_adapter_client.h" #include "web_contents_view_qt.h" - -#include <QVariant> +#include "net/resource_request_body_qt.h" // originally based on aw_proxying_url_loader_factory.cc: // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +namespace { + network::mojom::URLResponseHeadPtr createResponse(const network::ResourceRequest &request) { + const bool disable_web_security = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebSecurity); + network::mojom::URLResponseHeadPtr response = network::mojom::URLResponseHead::New(); + response->response_type = network::cors::CalculateResponseType( + request.mode, disable_web_security || ( + request.request_initiator && request.request_initiator->IsSameOriginWith(url::Origin::Create(request.url)))); + + return response; + } +} + namespace QtWebEngineCore { ASSERT_ENUMS_MATCH(QWebEngineUrlRequestInfo::ResourceTypeMainFrame, blink::mojom::ResourceType::kMainFrame) @@ -108,17 +81,28 @@ static QWebEngineUrlRequestInfo::NavigationType toQt(WebContentsAdapterClient::N return static_cast<QWebEngineUrlRequestInfo::NavigationType>(navigationType); } +static QHash<QByteArray, QByteArray> toQt(const net::HttpRequestHeaders &headers) +{ + const auto vector = headers.GetHeaderVector(); + QHash<QByteArray, QByteArray> hash; + + for (const auto &header : vector) { + hash.insert(QByteArray::fromStdString(header.key), QByteArray::fromStdString(header.value)); + } + + return hash; +} + // Handles intercepted, in-progress requests/responses, so that they can be // controlled and modified accordingly. class InterceptedRequest : public network::mojom::URLLoader , public network::mojom::URLLoaderClient { public: - InterceptedRequest(int process_id, uint64_t request_id, int32_t routing_id, uint32_t options, + InterceptedRequest(ProfileAdapter *profile_adapter, + int frame_tree_node_id, int32_t request_id, uint32_t options, const network::ResourceRequest &request, const net::MutableNetworkTrafficAnnotationTag &traffic_annotation, - QWebEngineUrlRequestInterceptor *profile_request_interceptor, - QWebEngineUrlRequestInterceptor *page_request_interceptor, mojo::PendingReceiver<network::mojom::URLLoader> loader, mojo::PendingRemote<network::mojom::URLLoaderClient> client, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory); @@ -127,24 +111,24 @@ public: void Restart(); // network::mojom::URLLoaderClient - void OnReceiveResponse(network::mojom::URLResponseHeadPtr head) override; + void OnReceiveResponse(network::mojom::URLResponseHeadPtr head, mojo::ScopedDataPipeConsumerHandle, absl::optional<mojo_base::BigBuffer>) override; void OnReceiveRedirect(const net::RedirectInfo &redirect_info, network::mojom::URLResponseHeadPtr head) override; void OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback callback) override; - void OnReceiveCachedMetadata(mojo_base::BigBuffer data) override; void OnTransferSizeUpdated(int32_t transfer_size_diff) override; - void OnStartLoadingResponseBody(mojo::ScopedDataPipeConsumerHandle body) override; void OnComplete(const network::URLLoaderCompletionStatus &status) override; + void OnReceiveEarlyHints(network::mojom::EarlyHintsPtr) override {} // network::mojom::URLLoader void FollowRedirect(const std::vector<std::string> &removed_headers, - const net::HttpRequestHeaders &modified_headers, const base::Optional<GURL> &new_url) override; + const net::HttpRequestHeaders &modified_headers, + const net::HttpRequestHeaders &modified_cors_exempt_headers, + const absl::optional<GURL> &new_url) override; void SetPriority(net::RequestPriority priority, int32_t intra_priority_value) override; void PauseReadingBodyFromNet() override; void ResumeReadingBodyFromNet() override; private: void InterceptOnUIThread(); - void InterceptOnIOThread(base::WaitableEvent *event); void ContinueAfterIntercept(); // This is called when the original URLLoaderClient has a connection error. @@ -160,25 +144,39 @@ private: void SendErrorAndCompleteImmediately(int error_code); - const int process_id_; - const uint64_t request_id_; - const int32_t routing_id_; + content::WebContents* webContents(); + QWebEngineUrlRequestInterceptor* getProfileInterceptor(); + QWebEngineUrlRequestInterceptor* getPageInterceptor(); + + QPointer<ProfileAdapter> profile_adapter_; + const int frame_tree_node_id_; + const int32_t request_id_; const uint32_t options_; - bool input_stream_previously_failed_ = false; - bool request_was_redirected_ = false; + bool allow_local_ = false; + bool allow_remote_ = true; + bool local_access_ = false; + bool remote_access_ = true; + + bool loader_error_seen_ = false; // If the |target_loader_| called OnComplete with an error this stores it. // That way the destructor can send it to OnReceivedError if safe browsing // error didn't occur. int error_status_ = net::OK; network::ResourceRequest request_; + ResourceRequestBody request_body_; network::mojom::URLResponseHeadPtr current_response_; const net::MutableNetworkTrafficAnnotationTag traffic_annotation_; - QWebEngineUrlRequestInfo request_info_; - QPointer<QWebEngineUrlRequestInterceptor> profile_request_interceptor_; - QPointer<QWebEngineUrlRequestInterceptor> page_request_interceptor_; + struct RequestInfoDeleter + { + void operator()(QWebEngineUrlRequestInfo *ptr) const + { delete ptr; } + }; + + std::unique_ptr<QWebEngineUrlRequestInfo, RequestInfoDeleter> request_info_; + mojo::Receiver<network::mojom::URLLoader> proxied_loader_receiver_; mojo::Remote<network::mojom::URLLoaderClient> target_client_; mojo::Receiver<network::mojom::URLLoaderClient> proxied_client_receiver_{this}; @@ -186,36 +184,52 @@ private: mojo::Remote<network::mojom::URLLoaderFactory> target_factory_; base::WeakPtrFactory<InterceptedRequest> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(InterceptedRequest); }; -InterceptedRequest::InterceptedRequest(int process_id, uint64_t request_id, int32_t routing_id, uint32_t options, +InterceptedRequest::InterceptedRequest(ProfileAdapter *profile_adapter, + int frame_tree_node_id, int32_t request_id, uint32_t options, const network::ResourceRequest &request, const net::MutableNetworkTrafficAnnotationTag &traffic_annotation, - QWebEngineUrlRequestInterceptor *profile_request_interceptor, - QWebEngineUrlRequestInterceptor *page_request_interceptor, mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderClient> client, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory) - : process_id_(process_id) + : profile_adapter_(profile_adapter) + , frame_tree_node_id_(frame_tree_node_id) , request_id_(request_id) - , routing_id_(routing_id) , options_(options) , request_(request) + , request_body_(ResourceRequestBody(request_.request_body.get())) , traffic_annotation_(traffic_annotation) - , profile_request_interceptor_(profile_request_interceptor) - , page_request_interceptor_(page_request_interceptor) , proxied_loader_receiver_(this, std::move(loader_receiver)) , target_client_(std::move(client)) , target_factory_(std::move(target_factory)) , weak_factory_(this) { - current_response_ = network::mojom::URLResponseHead::New(); + const bool disable_web_security = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebSecurity); + current_response_ = createResponse(request_); // If there is a client error, clean up the request. target_client_.set_disconnect_handler( - base::BindOnce(&InterceptedRequest::OnURLLoaderClientError, weak_factory_.GetWeakPtr())); + base::BindOnce(&InterceptedRequest::OnURLLoaderClientError, base::Unretained(this))); proxied_loader_receiver_.set_disconnect_with_reason_handler( - base::BindOnce(&InterceptedRequest::OnURLLoaderError, weak_factory_.GetWeakPtr())); + base::BindOnce(&InterceptedRequest::OnURLLoaderError, base::Unretained(this))); + if (!disable_web_security && request_.request_initiator) { + const std::vector<std::string> &localSchemes = url::GetLocalSchemes(); + const std::string fromScheme = request_.request_initiator->GetTupleOrPrecursorTupleIfOpaque().scheme(); + const std::string toScheme = request_.url.scheme(); + const bool fromLocal = base::Contains(localSchemes, fromScheme); + const bool toLocal = base::Contains(localSchemes, toScheme); + bool hasLocalAccess = false; + local_access_ = toLocal; + remote_access_ = !toLocal && (toScheme != "data") && (toScheme != "qrc"); + if (const url::CustomScheme *cs = url::CustomScheme::FindScheme(fromScheme)) + hasLocalAccess = cs->flags & url::CustomScheme::LocalAccessAllowed; + if (fromLocal || toLocal) { + content::WebContents *wc = webContents(); + // local schemes must have universal access, or be accessing something local and have local access. + allow_local_ = hasLocalAccess || (fromLocal && wc && wc->GetOrCreateWebPreferences().allow_file_access_from_file_urls); + allow_remote_ = !fromLocal || (wc && wc->GetOrCreateWebPreferences().allow_remote_access_from_local_urls); + } + } } InterceptedRequest::~InterceptedRequest() @@ -223,115 +237,175 @@ InterceptedRequest::~InterceptedRequest() weak_factory_.InvalidateWeakPtrs(); } +content::WebContents* InterceptedRequest::webContents() +{ + if (frame_tree_node_id_ == content::RenderFrameHost::kNoFrameTreeNodeId) + return nullptr; + return content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_); +} + +QWebEngineUrlRequestInterceptor* InterceptedRequest::getProfileInterceptor() +{ + return profile_adapter_ ? profile_adapter_->requestInterceptor() : nullptr; +} + +QWebEngineUrlRequestInterceptor* InterceptedRequest::getPageInterceptor() +{ + if (auto wc = webContents()) { + auto view = static_cast<content::WebContentsImpl *>(wc)->GetView(); + if (WebContentsAdapterClient *client = WebContentsViewQt::from(view)->client()) + return client->webContentsAdapter()->requestInterceptor(); + } + return nullptr; +} + void InterceptedRequest::Restart() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - blink::mojom::ResourceType resourceType = blink::mojom::ResourceType(request_.resource_type); - WebContentsAdapterClient::NavigationType navigationType = - pageTransitionToNavigationType(ui::PageTransition(request_.transition_type)); - const QUrl originalUrl = toQt(request_.url); - const QUrl initiator = request_.request_initiator.has_value() ? toQt(request_.request_initiator->GetURL()) : QUrl(); + bool granted_special_access = false; + auto navigationType = toQt(pageTransitionToNavigationType(ui::PageTransition(request_.transition_type))); + switch (navigationType) { + case QWebEngineUrlRequestInfo::NavigationTypeLink: + case QWebEngineUrlRequestInfo::NavigationTypeTyped: + if (blink::mojom::ResourceType(request_.resource_type) == blink::mojom::ResourceType::kMainFrame && request_.has_user_gesture) + granted_special_access = true; // allow normal explicit navigation + break; + case QWebEngineUrlRequestInfo::NavigationTypeBackForward: + case QWebEngineUrlRequestInfo::NavigationTypeReload: + if (blink::mojom::ResourceType(request_.resource_type) == blink::mojom::ResourceType::kMainFrame) + granted_special_access = true; + break; + default: + break; + } - content::WebContents *webContents = nullptr; - if (process_id_) { - content::RenderFrameHost *frameHost = content::RenderFrameHost::FromID(process_id_, request_.render_frame_id); - webContents = content::WebContents::FromRenderFrameHost(frameHost); - } else { - webContents = content::WebContents::FromFrameTreeNodeId(request_.render_frame_id); + // Check if non-local access is allowed + if (!allow_remote_ && remote_access_) { + if (!granted_special_access) { + target_client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_NETWORK_ACCESS_DENIED)); + delete this; + return; + } + } + + // Check if local access is allowed + if (!allow_local_ && local_access_) { + // Check for specifically granted file access: + if (auto *frame_tree = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id_)) { + const int renderer_id = frame_tree->current_frame_host()->GetProcess()->GetID(); + base::FilePath file_path; + if (net::FileURLToFilePath(request_.url, &file_path)) { + if (content::ChildProcessSecurityPolicy::GetInstance()->CanReadFile(renderer_id, file_path)) + granted_special_access = true; + } + } + if (!granted_special_access) { + target_client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED)); + delete this; + return; + } + } + + // MEMO since all codepatch leading to Restart scheduled and executed as asynchronous tasks in main thread, + // interceptors may change in meantime and also during intercept call, so they should be resolved anew. + // Set here only profile's interceptor since it runs first without going to user code. + auto profileInterceptor = getProfileInterceptor(); + if (!profileInterceptor && !getPageInterceptor()) { + ContinueAfterIntercept(); + return; } - GURL top_document_url = webContents ? webContents->GetVisibleURL() : GURL(); + auto resourceType = toQt(blink::mojom::ResourceType(request_.resource_type)); + const QUrl originalUrl = toQt(request_.url); + const QUrl initiator = request_.request_initiator.has_value() ? toQt(request_.request_initiator->GetURL()) : QUrl(); + + auto wc = webContents(); + GURL top_document_url = wc ? wc->GetVisibleURL() : GURL(); QUrl firstPartyUrl; if (!top_document_url.is_empty()) firstPartyUrl = toQt(top_document_url); else - firstPartyUrl = toQt(request_.site_for_cookies.RepresentativeUrl()); // m_topDocumentUrl can be empty for the main-frame. - - QWebEngineUrlRequestInfoPrivate *infoPrivate = - new QWebEngineUrlRequestInfoPrivate(toQt(resourceType), toQt(navigationType), originalUrl, firstPartyUrl, - initiator, QByteArray::fromStdString(request_.method)); - request_info_ = QWebEngineUrlRequestInfo(infoPrivate); - - // TODO: remove for Qt6 - if (profile_request_interceptor_ && profile_request_interceptor_->property("deprecated").toBool()) { - // sync call supports depracated call of an interceptor on io thread - base::WaitableEvent event; - base::PostTask(FROM_HERE, { content::BrowserThread::IO }, - base::BindOnce(&InterceptedRequest::InterceptOnIOThread, base::Unretained(this), &event)); - event.Wait(); - if (request_info_.changed()) { - ContinueAfterIntercept(); - return; - } - } + firstPartyUrl = toQt(request_.site_for_cookies.first_party_url()); // m_topDocumentUrl can be empty for the main-frame. + + QHash<QByteArray, QByteArray> headers = toQt(request_.headers); + + if (!request_.referrer.is_empty()) + headers.insert("Referer", toQt(request_.referrer).toEncoded()); + + auto info = new QWebEngineUrlRequestInfoPrivate( + resourceType, navigationType, originalUrl, firstPartyUrl, initiator, + QByteArray::fromStdString(request_.method), &request_body_, headers); + Q_ASSERT(!request_info_); + request_info_.reset(new QWebEngineUrlRequestInfo(info)); + InterceptOnUIThread(); ContinueAfterIntercept(); } -void InterceptedRequest::InterceptOnIOThread(base::WaitableEvent *event) -{ - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - if (profile_request_interceptor_) - profile_request_interceptor_->interceptRequest(request_info_); - event->Signal(); -} - void InterceptedRequest::InterceptOnUIThread() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (profile_request_interceptor_ && !profile_request_interceptor_->property("deprecated").toBool()) - profile_request_interceptor_->interceptRequest(request_info_); + if (auto interceptor = getProfileInterceptor()) + interceptor->interceptRequest(*request_info_); - if (!request_info_.changed() && page_request_interceptor_) - page_request_interceptor_->interceptRequest(request_info_); + if (!request_info_->changed()) { + if (auto interceptor = getPageInterceptor()) + interceptor->interceptRequest(*request_info_); + } } void InterceptedRequest::ContinueAfterIntercept() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (request_info_.changed()) { - if (request_info_.d_ptr->shouldBlockRequest) - return SendErrorAndCompleteImmediately(net::ERR_BLOCKED_BY_CLIENT); - if (request_info_.d_ptr->shouldRedirectRequest) { - net::URLRequest::FirstPartyURLPolicy first_party_url_policy = - request_.update_first_party_url_on_redirect ? net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT - : net::URLRequest::NEVER_CHANGE_FIRST_PARTY_URL; - net::RedirectInfo redirectInfo = net::RedirectInfo::ComputeRedirectInfo( - request_.method, request_.url, request_.site_for_cookies, - first_party_url_policy, request_.referrer_policy, request_.referrer.spec(), - net::HTTP_TEMPORARY_REDIRECT, toGurl(request_info_.requestUrl()), base::nullopt, - false /*insecure_scheme_was_upgraded*/); - - // FIXME: Should probably create a new header. - current_response_->encoded_data_length = 0; - request_.method = redirectInfo.new_method; - request_.url = redirectInfo.new_url; - request_.site_for_cookies = redirectInfo.new_site_for_cookies; - request_.referrer = GURL(redirectInfo.new_referrer); - request_.referrer_policy = redirectInfo.new_referrer_policy; - if (request_.method == net::HttpRequestHeaders::kGetMethod) - request_.request_body = nullptr; - target_client_->OnReceiveRedirect(redirectInfo, std::move(current_response_)); - return; + if (request_info_) { + // cleanup in scope because of delete this and it's not needed else where after + const auto scoped_request_info = std::move(request_info_); + QWebEngineUrlRequestInfoPrivate &info = *scoped_request_info->d_ptr; + + for (auto header = info.extraHeaders.constBegin(); header != info.extraHeaders.constEnd(); ++header) { + std::string h = header.key().toStdString(); + if (base::EqualsCaseInsensitiveASCII(h, "referer")) + request_.referrer = GURL(header.value().toStdString()); + else + request_.headers.SetHeader(h, header.value().toStdString()); } - if (!request_info_.d_ptr->extraHeaders.isEmpty()) { - auto end = request_info_.d_ptr->extraHeaders.constEnd(); - for (auto header = request_info_.d_ptr->extraHeaders.constBegin(); header != end; ++header) { - std::string h = header.key().toStdString(); - if (base::LowerCaseEqualsASCII(h, "referer")) { - request_.referrer = GURL(header.value().toStdString()); - } else { - request_.headers.SetHeader(h, header.value().toStdString()); - } + if (info.changed) { + if (info.shouldBlockRequest) + return SendErrorAndCompleteImmediately(net::ERR_BLOCKED_BY_CLIENT); + + if (info.shouldRedirectRequest) { + net::RedirectInfo::FirstPartyURLPolicy first_party_url_policy = + request_.update_first_party_url_on_redirect ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT + : net::RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL; + net::RedirectInfo redirectInfo = net::RedirectInfo::ComputeRedirectInfo( + request_.method, request_.url, request_.site_for_cookies, + first_party_url_policy, request_.referrer_policy, request_.referrer.spec(), + net::HTTP_TEMPORARY_REDIRECT, toGurl(info.url), absl::nullopt, + false /*insecure_scheme_was_upgraded*/); + request_.method = redirectInfo.new_method; + request_.url = redirectInfo.new_url; + request_.site_for_cookies = redirectInfo.new_site_for_cookies; + request_.referrer = GURL(redirectInfo.new_referrer); + request_.referrer_policy = redirectInfo.new_referrer_policy; + if (request_.method == net::HttpRequestHeaders::kGetMethod) + request_.request_body = nullptr; + // In case of multiple sequential rediredts, current_response_ has previously been moved to target_client_ + // so we create a new one using the redirect url. + if (!current_response_) + current_response_ = createResponse(request_); + current_response_->encoded_data_length = 0; + target_client_->OnReceiveRedirect(redirectInfo, std::move(current_response_)); + return; } } } if (!target_loader_ && target_factory_) { - target_factory_->CreateLoaderAndStart(target_loader_.BindNewPipeAndPassReceiver(), routing_id_, request_id_, + loader_error_seen_ = false; + target_factory_->CreateLoaderAndStart(target_loader_.BindNewPipeAndPassReceiver(), request_id_, options_, request_, proxied_client_receiver_.BindNewPipeAndPassRemote(), traffic_annotation_); } @@ -339,17 +413,16 @@ void InterceptedRequest::ContinueAfterIntercept() // URLLoaderClient methods. -void InterceptedRequest::OnReceiveResponse(network::mojom::URLResponseHeadPtr head) +void InterceptedRequest::OnReceiveResponse(network::mojom::URLResponseHeadPtr head, mojo::ScopedDataPipeConsumerHandle handle, absl::optional<mojo_base::BigBuffer> buffer) { current_response_ = head.Clone(); - target_client_->OnReceiveResponse(std::move(head)); + target_client_->OnReceiveResponse(std::move(head), std::move(handle), std::move(buffer)); } void InterceptedRequest::OnReceiveRedirect(const net::RedirectInfo &redirect_info, network::mojom::URLResponseHeadPtr head) { // TODO(timvolodine): handle redirect override. - request_was_redirected_ = true; current_response_ = head.Clone(); target_client_->OnReceiveRedirect(redirect_info, std::move(head)); request_.url = redirect_info.new_url; @@ -364,21 +437,11 @@ void InterceptedRequest::OnUploadProgress(int64_t current_position, int64_t tota target_client_->OnUploadProgress(current_position, total_size, std::move(callback)); } -void InterceptedRequest::OnReceiveCachedMetadata(mojo_base::BigBuffer data) -{ - target_client_->OnReceiveCachedMetadata(std::move(data)); -} - void InterceptedRequest::OnTransferSizeUpdated(int32_t transfer_size_diff) { target_client_->OnTransferSizeUpdated(transfer_size_diff); } -void InterceptedRequest::OnStartLoadingResponseBody(mojo::ScopedDataPipeConsumerHandle body) -{ - target_client_->OnStartLoadingResponseBody(std::move(body)); -} - void InterceptedRequest::OnComplete(const network::URLLoaderCompletionStatus &status) { // Only wait for the original loader to possibly have a custom error if the @@ -391,10 +454,11 @@ void InterceptedRequest::OnComplete(const network::URLLoaderCompletionStatus &st void InterceptedRequest::FollowRedirect(const std::vector<std::string> &removed_headers, const net::HttpRequestHeaders &modified_headers, - const base::Optional<GURL> &new_url) + const net::HttpRequestHeaders &modified_cors_exempt_headers, + const absl::optional<GURL> &new_url) { if (target_loader_) - target_loader_->FollowRedirect(removed_headers, modified_headers, new_url); + target_loader_->FollowRedirect(removed_headers, modified_headers, modified_cors_exempt_headers, new_url); // If |OnURLLoaderClientError| was called then we're just waiting for the // connection error handler of |proxied_loader_binding_|. Don't restart the @@ -436,6 +500,8 @@ void InterceptedRequest::OnURLLoaderError(uint32_t custom_reason, const std::str // If CallOnComplete was already called, then this object is ready to be deleted. if (!target_client_) delete this; + else + loader_error_seen_ = true; } void InterceptedRequest::CallOnComplete(const network::URLLoaderCompletionStatus &status, bool wait_for_loader_error) @@ -449,7 +515,7 @@ void InterceptedRequest::CallOnComplete(const network::URLLoaderCompletionStatus if (target_client_) target_client_->OnComplete(status); - if (proxied_loader_receiver_.is_bound() && wait_for_loader_error) { + if (proxied_loader_receiver_.is_bound() && wait_for_loader_error && !loader_error_seen_) { // Since the original client is gone no need to continue loading the // request. proxied_client_receiver_.reset(); @@ -478,10 +544,10 @@ void InterceptedRequest::SendErrorAndCompleteImmediately(int error_code) delete this; } -ProxyingURLLoaderFactoryQt::ProxyingURLLoaderFactoryQt(int process_id, QWebEngineUrlRequestInterceptor *profile, QWebEngineUrlRequestInterceptor *page, +ProxyingURLLoaderFactoryQt::ProxyingURLLoaderFactoryQt(ProfileAdapter *adapter, int frame_tree_node_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_info) - : m_processId(process_id), m_profileRequestInterceptor(profile), m_pageRequestInterceptor(page), m_weakFactory(this) + : m_profileAdapter(adapter), m_frameTreeNodeId(frame_tree_node_id), m_weakFactory(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (target_factory_info) { @@ -499,8 +565,8 @@ ProxyingURLLoaderFactoryQt::~ProxyingURLLoaderFactoryQt() m_weakFactory.InvalidateWeakPtrs(); } -void ProxyingURLLoaderFactoryQt::CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t routing_id, - int32_t request_id, uint32_t options, const network::ResourceRequest &request, +void ProxyingURLLoaderFactoryQt::CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, + uint32_t options, const network::ResourceRequest &request, mojo::PendingRemote<network::mojom::URLLoaderClient> url_loader_client, const net::MutableNetworkTrafficAnnotationTag &traffic_annotation) { @@ -510,8 +576,8 @@ void ProxyingURLLoaderFactoryQt::CreateLoaderAndStart(mojo::PendingReceiver<netw m_targetFactory->Clone(target_factory_clone.InitWithNewPipeAndPassReceiver()); // Will manage its own lifetime - InterceptedRequest *req = new InterceptedRequest(m_processId, request_id, routing_id, options, request, traffic_annotation, - m_profileRequestInterceptor, m_pageRequestInterceptor, std::move(loader), + InterceptedRequest *req = new InterceptedRequest(m_profileAdapter, m_frameTreeNodeId, request_id, options, + request, traffic_annotation, std::move(loader), std::move(url_loader_client), std::move(target_factory_clone)); req->Restart(); } diff --git a/src/core/net/proxying_url_loader_factory_qt.h b/src/core/net/proxying_url_loader_factory_qt.h index e1bcc276c..904a40c2d 100644 --- a/src/core/net/proxying_url_loader_factory_qt.h +++ b/src/core/net/proxying_url_loader_factory_qt.h @@ -1,57 +1,14 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef PROXYING_URL_LOADER_FACTORY_QT_H_ #define PROXYING_URL_LOADER_FACTORY_QT_H_ -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/ref_counted_delete_on_sequence.h" #include "base/memory/weak_ptr.h" -#include "base/optional.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "net/traffic_annotation/network_traffic_annotation.h" -#include "services/network/public/cpp/resource_request.h" #include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "url/gurl.h" #include <QPointer> // based on aw_proxying_url_loader_factory.h: @@ -59,26 +16,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -QT_FORWARD_DECLARE_CLASS(QWebEngineUrlRequestInterceptor) - -namespace content { -class ResourceContext; +namespace network { +struct ResourceRequest; } namespace QtWebEngineCore { +class ProfileAdapter; + class ProxyingURLLoaderFactoryQt : public network::mojom::URLLoaderFactory { public: - ProxyingURLLoaderFactoryQt(int processId, QWebEngineUrlRequestInterceptor *profile, - QWebEngineUrlRequestInterceptor *page, + ProxyingURLLoaderFactoryQt(ProfileAdapter *adapter, int frameTreeNodeId, mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_target_factory_remote); ~ProxyingURLLoaderFactoryQt() override; void CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> loader, - int32_t routing_id, int32_t request_id, + int32_t request_id, uint32_t options, const network::ResourceRequest &request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag &traffic_annotation) override; @@ -89,14 +45,11 @@ private: void OnTargetFactoryError(); void OnProxyBindingError(); - int m_processId; + QPointer<ProfileAdapter> m_profileAdapter; + int m_frameTreeNodeId; mojo::ReceiverSet<network::mojom::URLLoaderFactory> m_proxyReceivers; mojo::Remote<network::mojom::URLLoaderFactory> m_targetFactory; - QPointer<QWebEngineUrlRequestInterceptor> m_profileRequestInterceptor; - QPointer<QWebEngineUrlRequestInterceptor> m_pageRequestInterceptor; base::WeakPtrFactory<ProxyingURLLoaderFactoryQt> m_weakFactory; - - DISALLOW_COPY_AND_ASSIGN(ProxyingURLLoaderFactoryQt); }; } // namespace QtWebEngineCore diff --git a/src/core/net/qrc_url_scheme_handler.cpp b/src/core/net/qrc_url_scheme_handler.cpp index 73bf24f1d..a8b4e4388 100644 --- a/src/core/net/qrc_url_scheme_handler.cpp +++ b/src/core/net/qrc_url_scheme_handler.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2018 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2018 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qrc_url_scheme_handler.h" @@ -46,6 +10,8 @@ #include <QMimeDatabase> #include <QMimeType> +#include <memory> + namespace QtWebEngineCore { void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job) @@ -58,7 +24,7 @@ void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job) QUrl requestUrl = job->requestUrl(); QString requestPath = requestUrl.path(); - QScopedPointer<QFile> file(new QFile(':' + requestPath, job)); + auto file = std::make_unique<QFile>(':' + requestPath, job); if (!file->exists() || file->size() == 0) { qWarning("QResource '%s' not found or is empty", qUtf8Printable(requestPath)); job->fail(QWebEngineUrlRequestJob::UrlNotFound); @@ -67,7 +33,10 @@ void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job) QFileInfo fileInfo(*file); QMimeDatabase mimeDatabase; QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileInfo); - job->reply(mimeType.name().toUtf8(), file.take()); + if (mimeType.name() == QStringLiteral("application/x-extension-html")) + job->reply("text/html", file.release()); + else + job->reply(mimeType.name().toUtf8(), file.release()); } } // namespace QtWebEngineCore diff --git a/src/core/net/qrc_url_scheme_handler.h b/src/core/net/qrc_url_scheme_handler.h index 586147cdf..96155b05b 100644 --- a/src/core/net/qrc_url_scheme_handler.h +++ b/src/core/net/qrc_url_scheme_handler.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2018 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2018 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QRC_URL_SCHEME_HANDLER_H #define QRC_URL_SCHEME_HANDLER_H diff --git a/src/core/net/resource_request_body_qt.cpp b/src/core/net/resource_request_body_qt.cpp new file mode 100644 index 000000000..d0d54784d --- /dev/null +++ b/src/core/net/resource_request_body_qt.cpp @@ -0,0 +1,181 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "resource_request_body_qt.h" +#include "type_conversion.h" + +#include "services/network/public/cpp/resource_request_body.h" +#include "services/network/public/mojom/data_pipe_getter.mojom.h" +#include "services/network/public/mojom/url_request.mojom-shared.h" +#include "mojo/public/cpp/bindings/remote.h" + +namespace QtWebEngineCore { + +ResourceRequestBody::ResourceRequestBody(network::ResourceRequestBody *requestBody, QObject *parent) + : QIODevice(parent) + , m_requestBody(requestBody) + , m_dataElementsIdx(0) + , m_dataElementBytesIdx(0) + , m_dataElementFileIdx(0) +{}; + +ResourceRequestBody::~ResourceRequestBody(){}; + +qint64 ResourceRequestBody::readData(char *data, qint64 maxSize) +{ + if (!m_requestBody) + return -1; + + const std::size_t dataElementsSize = m_requestBody->elements()->size(); + if (m_dataElementsIdx == dataElementsSize) + return -1; + + qint64 bytesRead = 0; + const std::vector<network::DataElement> *elements = m_requestBody->elements(); + while (bytesRead < maxSize && m_dataElementsIdx < dataElementsSize) { + const network::DataElement ¤tDataElement = elements->at(m_dataElementsIdx); + + switch (currentDataElement.type()) { + case network::mojom::DataElementDataView::Tag::kBytes: { + readDataElementBytes(currentDataElement.As<network::DataElementBytes>().bytes(), + bytesRead, maxSize, &data); + break; + } + case network::mojom::DataElementDataView::Tag::kFile: { + const network::DataElementFile file = currentDataElement.As<network::DataElementFile>(); + const qint64 offset = file.offset(); + const qint64 length = file.length(); + readDataElementFile(file.path(), offset, length, bytesRead, maxSize, &data); + break; + } + case network::mojom::DataElementDataView::Tag::kDataPipe: { + mojo::Remote<network::mojom::DataPipeGetter> pipeGetter; + pipeGetter.Bind( + currentDataElement.As<network::DataElementDataPipe>().CloneDataPipeGetter()); + const mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> consumerHandle = + getConsumerHandleFromPipeGetter(pipeGetter); + readDataElementPipe(consumerHandle, bytesRead, maxSize, &data); + break; + } + case network::mojom::DataElementDataView::Tag::kChunkedDataPipe: { + setErrorString(QStringLiteral("Chunked data pipe is used in request body upload, which " + "is currently not supported")); + // Nothing should come before or after DataElementChunkedDataPipe + return -1; + } + } + + if (bytesRead == maxSize || m_dataElementsIdx == dataElementsSize) + break; + } + + return bytesRead; +} + +// We don't want to write, ever +qint64 ResourceRequestBody::writeData(const char *data, qint64 maxSize) +{ + return -1; +} + +bool ResourceRequestBody::isSequential() const +{ + return true; +} + +void ResourceRequestBody::readDataElementBytes(const std::vector<uint8_t> &dataElement, + qint64 &bytesRead, const qint64 &maxSize, + char **data) +{ + const std::size_t dataElementSize = dataElement.size(); + const std::size_t bytesToRead = std::min(dataElementSize, static_cast<std::size_t>(maxSize)); + + std::memcpy(*data, dataElement.data(), bytesToRead); + *data += bytesToRead; + m_dataElementBytesIdx += bytesToRead; + bytesRead += bytesToRead; + + if (m_dataElementBytesIdx == dataElementSize) { + m_dataElementsIdx++; + m_dataElementBytesIdx = 0; + } +} + +void ResourceRequestBody::readDataElementFile(const base::FilePath &filePath, const qint64 &offset, + const qint64 &length, qint64 &bytesRead, + const qint64 &maxSize, char **data) +{ + QFile file(toQt(filePath.value())); + const qint64 realOffset = offset + m_dataElementFileIdx; + const std::size_t fileSize = std::min(file.size(), length) - realOffset; + const std::size_t bytesToRead = std::min(fileSize, static_cast<std::size_t>(maxSize)); + + file.open(QFile::ReadOnly); + file.seek(realOffset); + + std::memcpy(*data, file.read(bytesToRead).data(), bytesToRead); + *data += bytesToRead; + m_dataElementFileIdx += bytesToRead; + bytesRead += bytesToRead; + + file.close(); + + if (m_dataElementFileIdx == fileSize) { + m_dataElementsIdx++; + m_dataElementFileIdx = 0; + } +} + +mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> +ResourceRequestBody::getConsumerHandleFromPipeGetter( + mojo::Remote<network::mojom::DataPipeGetter> &pipeGetter) +{ + mojo::ScopedHandleBase<mojo::DataPipeProducerHandle> producerHandle; + mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> consumerHandle; + mojo::CreateDataPipe(nullptr, producerHandle, consumerHandle); + base::WeakPtrFactory<ResourceRequestBody> weakPtrFactory{ this }; + pipeGetter->Read(std::move(producerHandle), + base::BindOnce(&ResourceRequestBody::pipeGetterOnReadComplete, + weakPtrFactory.GetWeakPtr())); + + return consumerHandle; +} + +void ResourceRequestBody::readDataElementPipe( + const mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> &consumerHandle, + qint64 &bytesRead, const qint64 &maxSize, char **data) +{ + MojoResult result; + do { + uint32_t bytesToRead = 1; + result = consumerHandle->ReadData(*data, &bytesToRead, MOJO_READ_DATA_FLAG_NONE); + + if (result == MOJO_RESULT_OK) { + *data += bytesToRead; + bytesRead += bytesToRead; + } else if (result != MOJO_RESULT_SHOULD_WAIT && result != MOJO_RESULT_FAILED_PRECONDITION) { + setErrorString(QString::fromLatin1("Error while reading from data pipe, skipping" + "remaining content of data pipe. Mojo error code: ") + + QString::number(result)); + } + } while ((result == MOJO_RESULT_SHOULD_WAIT || result == MOJO_RESULT_OK) + && bytesRead < maxSize); + + m_dataElementsIdx++; +} + +void ResourceRequestBody::pipeGetterOnReadComplete(int32_t status, uint64_t size) { } + +void ResourceRequestBody::appendFilesForTest(const QString &path) +{ + if (!m_requestBody) + return; + + base::FilePath filePath = toFilePath(path); + m_requestBody->elements_mutable()->push_back(static_cast<network::DataElement>( + network::DataElementFile(filePath, 0, 23, base::Time()))); + m_requestBody->elements_mutable()->push_back(static_cast<network::DataElement>( + network::DataElementFile(filePath, 10, 23, base::Time()))); +} + +} // namespace QtWebEngineCore diff --git a/src/core/net/resource_request_body_qt.h b/src/core/net/resource_request_body_qt.h new file mode 100644 index 000000000..717885d7d --- /dev/null +++ b/src/core/net/resource_request_body_qt.h @@ -0,0 +1,70 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef RESOURCEREQUESTBODY_QT_H +#define RESOURCEREQUESTBODY_QT_H + +#include <QtWebEngineCore/private/qtwebenginecoreglobal_p.h> +#include <QtCore/QIODevice> +#include <QtCore/QFile> +#include <QtCore/QUrl> + +namespace network { +class ResourceRequestBody; +namespace mojom { +class DataPipeGetter; +class ChunkedDataPipeGetter; +} +} + +namespace base { +class FilePath; +} + +namespace mojo { +template<typename T> +class Remote; +template<typename T> +class ScopedHandleBase; +class DataPipeConsumerHandle; +} + +namespace QtWebEngineCore { + +class Q_WEBENGINECORE_EXPORT ResourceRequestBody : public QIODevice +{ + Q_OBJECT +public: + explicit ResourceRequestBody(network::ResourceRequestBody *requestBody, + QObject *parent = nullptr); + ~ResourceRequestBody(); + + qint64 readData(char *data, qint64 maxSize) override; + qint64 writeData(const char *data, qint64 maxSize) override; + bool isSequential() const override; + + void appendFilesForTest(const QString &path); + +private: + network::ResourceRequestBody *const m_requestBody; + + std::size_t m_dataElementsIdx; + std::size_t m_dataElementBytesIdx; + std::size_t m_dataElementFileIdx; + + void readDataElementBytes(const std::vector<uint8_t> &dataElement, qint64 &bytesRead, + const qint64 &maxSize, char **data); + void readDataElementFile(const base::FilePath &filePath, const qint64 &offset, + const qint64 &length, qint64 &bytesRead, const qint64 &maxSize, + char **data); + mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> + getConsumerHandleFromPipeGetter(mojo::Remote<network::mojom::DataPipeGetter> &pipeGetter); + void + readDataElementPipe(const mojo::ScopedHandleBase<mojo::DataPipeConsumerHandle> &consumerHandle, + qint64 &bytesRead, const qint64 &maxSize, char **data); + void pipeGetterOnReadComplete(int32_t status, uint64_t size); +}; + +} // namespace QtWebEngineCore + +#endif // RESOURCEREQUESTBODY_QT_H diff --git a/src/core/net/ssl_host_state_delegate_qt.cpp b/src/core/net/ssl_host_state_delegate_qt.cpp index 3390c092a..41967f14e 100644 --- a/src/core/net/ssl_host_state_delegate_qt.cpp +++ b/src/core/net/ssl_host_state_delegate_qt.cpp @@ -1,47 +1,9 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "base/callback.h" +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "ssl_host_state_delegate_qt.h" -#include "type_conversion.h" +#include "base/functional/callback.h" namespace QtWebEngineCore { @@ -77,7 +39,7 @@ SSLHostStateDelegateQt::SSLHostStateDelegateQt() {} SSLHostStateDelegateQt::~SSLHostStateDelegateQt() {} -void SSLHostStateDelegateQt::AllowCert(const std::string &host, const net::X509Certificate &cert, int error, content::WebContents *) +void SSLHostStateDelegateQt::AllowCert(const std::string &host, const net::X509Certificate &cert, int error, content::StoragePartition *) { m_certPolicyforHost[host].Allow(cert, error); } @@ -105,7 +67,7 @@ void SSLHostStateDelegateQt::Clear(base::RepeatingCallback<bool(const std::strin // prior to this query, otherwise false. content::SSLHostStateDelegate::CertJudgment SSLHostStateDelegateQt::QueryPolicy(const std::string &host, const net::X509Certificate &cert, - int error, content::WebContents *) + int error, content::StoragePartition *) { return m_certPolicyforHost[host].Check(cert, error) ? SSLHostStateDelegate::ALLOWED : SSLHostStateDelegate::DENIED; } @@ -121,6 +83,16 @@ bool SSLHostStateDelegateQt::DidHostRunInsecureContent(const std::string &host, return false; } +void SSLHostStateDelegateQt::AllowHttpForHost(const std::string &host, content::StoragePartition *web_contents) +{ + // Intentional no-op see aw_ssl_host_state_delegate +} + +bool SSLHostStateDelegateQt::IsHttpAllowedForHost(const std::string &host, content::StoragePartition *web_contents) +{ + return false; +} + // Revokes all SSL certificate error allow exceptions made by the user for // |host|. void SSLHostStateDelegateQt::RevokeUserAllowExceptions(const std::string &host) @@ -132,12 +104,33 @@ void SSLHostStateDelegateQt::RevokeUserAllowExceptions(const std::string &host) // |host|. This does not mean that *all* certificate errors are allowed, just // that there exists an exception. To see if a particular certificate and // error combination exception is allowed, use QueryPolicy(). -bool SSLHostStateDelegateQt::HasAllowException(const std::string &host, content::WebContents *) +bool SSLHostStateDelegateQt::HasAllowException(const std::string &host, content::StoragePartition *) { auto policy_iterator = m_certPolicyforHost.find(host); return policy_iterator != m_certPolicyforHost.end() && policy_iterator->second.HasAllowException(); } +bool SSLHostStateDelegateQt::HasAllowExceptionForAnyHost(content::StoragePartition *storage_partition) +{ + for (auto const &it : m_certPolicyforHost) { + if (it.second.HasAllowException()) { + return true; + } + } + return false; +} + +void SSLHostStateDelegateQt::SetHttpsEnforcementForHost(const std::string &host, bool enforce, + content::StoragePartition *storage_partition) +{ + // Intentional no-op see aw_ssl_host_state_delegate +} + +bool SSLHostStateDelegateQt::IsHttpsEnforcedForHost(const std::string &host, content::StoragePartition *storage_partition) +{ + // Intentional no-op + return false; +} } // namespace QtWebEngineCore diff --git a/src/core/net/ssl_host_state_delegate_qt.h b/src/core/net/ssl_host_state_delegate_qt.h index 6b407353a..0b3d7974c 100644 --- a/src/core/net/ssl_host_state_delegate_qt.h +++ b/src/core/net/ssl_host_state_delegate_qt.h @@ -1,47 +1,13 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef SSL_HOST_STATE_DELEGATE_QT_H #define SSL_HOST_STATE_DELEGATE_QT_H #include "content/public/browser/ssl_host_state_delegate.h" -#include "profile_adapter.h" + +#include <map> +#include <string> namespace QtWebEngineCore { @@ -66,13 +32,18 @@ public: ~SSLHostStateDelegateQt(); // content::SSLHostStateDelegate implementation: - void AllowCert(const std::string &, const net::X509Certificate &cert, int error, content::WebContents *web_contents) override; + void AllowCert(const std::string &, const net::X509Certificate &cert, int error, content::StoragePartition *storage_partition) override; void Clear(base::RepeatingCallback<bool(const std::string&)> host_filter) override; - CertJudgment QueryPolicy(const std::string &host, const net::X509Certificate &cert, int error, content::WebContents *web_contents) override; + CertJudgment QueryPolicy(const std::string &host, const net::X509Certificate &cert, int error, content::StoragePartition *web_contents) override; void HostRanInsecureContent(const std::string &host, int child_id, InsecureContentType content_type) override; bool DidHostRunInsecureContent(const std::string &host, int child_id, InsecureContentType content_type) override; + void AllowHttpForHost(const std::string &host, content::StoragePartition *web_contents) override; + bool IsHttpAllowedForHost(const std::string &host, content::StoragePartition *web_contents) override; + void SetHttpsEnforcementForHost(const std::string &host, bool enforce, content::StoragePartition *storage_partition) override; + bool IsHttpsEnforcedForHost(const std::string &host, content::StoragePartition *web_contents) override; void RevokeUserAllowExceptions(const std::string &host) override; - bool HasAllowException(const std::string &host, content::WebContents *web_contents) override; + bool HasAllowException(const std::string &host, content::StoragePartition *web_contents) override; + bool HasAllowExceptionForAnyHost(content::StoragePartition *storage_partition) override; private: std::map<std::string, CertPolicy> m_certPolicyforHost; diff --git a/src/core/net/system_network_context_manager.cpp b/src/core/net/system_network_context_manager.cpp index 611b5eafa..439d1066c 100644 --- a/src/core/net/system_network_context_manager.cpp +++ b/src/core/net/system_network_context_manager.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2021 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // based on chrome/browser/net/system_network_context_manager.cc: // Copyright 2017 The Chromium Authors. All rights reserved. @@ -44,55 +8,47 @@ #include "net/system_network_context_manager.h" -#include <set> -#include <unordered_map> -#include <utility> - -#include "base/bind.h" #include "base/command_line.h" -#include "base/feature_list.h" -#include "base/logging.h" -#include "base/sequence_checker.h" +#include "base/functional/bind.h" #include "base/strings/string_split.h" -#include "base/task/post_task.h" -#include "base/values.h" -#include "build/build_config.h" #include "chrome/browser/net/chrome_mojo_proxy_resolver_factory.h" #include "chrome/common/chrome_switches.h" #include "components/certificate_transparency/ct_known_logs.h" -#include "components/network_session_configurator/common/network_features.h" #include "components/network_session_configurator/common/network_switches.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/cors_exempt_headers.h" #include "content/public/browser/network_service_instance.h" -#include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" -#include "content/public/common/service_names.mojom.h" -#include "content/public/common/user_agent.h" -#include "mojo/public/cpp/bindings/associated_interface_ptr.h" -#include "net/dns/public/util.h" +#include "crypto/sha2.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "net/base/port_util.h" #include "net/net_buildflags.h" -#include "net/third_party/uri_template/uri_template.h" +#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h" #include "services/network/network_service.h" #include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -#include "services/network/public/mojom/host_resolver.mojom.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "services/network/public/mojom/cert_verifier_service.mojom.h" +#include "services/network/public/mojom/network_context.mojom.h" #include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h" -#include "url/gurl.h" +#include "api/qwebengineglobalsettings.h" +#include "api/qwebengineglobalsettings_p.h" -namespace { +#if BUILDFLAG(IS_WIN) +#include "chrome/browser/net/chrome_mojo_proxy_resolver_win.h" +#include "components/os_crypt/sync/os_crypt.h" +#include "content/public/browser/network_service_util.h" +#endif -// The global instance of the SystemNetworkContextmanager. -SystemNetworkContextManager *g_system_network_context_manager = nullptr; +ASSERT_ENUMS_MATCH(net::SecureDnsMode::kSecure, QWebEngineGlobalSettings::SecureDnsMode::SecureOnly) +ASSERT_ENUMS_MATCH(net::SecureDnsMode::kAutomatic, + QWebEngineGlobalSettings::SecureDnsMode::SecureWithFallback) +ASSERT_ENUMS_MATCH(net::SecureDnsMode::kOff, QWebEngineGlobalSettings::SecureDnsMode::SystemOnly) + +namespace { network::mojom::HttpAuthStaticParamsPtr CreateHttpAuthStaticParams() { - network::mojom::HttpAuthStaticParamsPtr auth_static_params = network::mojom::HttpAuthStaticParams::New(); - - auth_static_params->supported_schemes = { "basic", "digest", "ntlm", "negotiate" }; + network::mojom::HttpAuthStaticParamsPtr auth_static_params = + network::mojom::HttpAuthStaticParams::New(); return auth_static_params; } @@ -101,8 +57,10 @@ network::mojom::HttpAuthDynamicParamsPtr CreateHttpAuthDynamicParams() { network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params = network::mojom::HttpAuthDynamicParams::New(); + auth_dynamic_params->allowed_schemes = { "basic", "digest", "ntlm", "negotiate" }; + auto *command_line = base::CommandLine::ForCurrentProcess(); - auth_dynamic_params->server_allowlist = command_line->GetSwitchValueASCII(switches::kAuthServerWhitelist); + auth_dynamic_params->server_allowlist = command_line->GetSwitchValueASCII(switches::kAuthServerAllowlist); // auth_dynamic_params->delegate_allowlist = command_line->GetSwitchValueASCII(switches::kAuthNegotiateDelegateWhitelist); // auth_dynamic_params->enable_negotiate_port = command_line->HasSwitch(switches::kEnableAuthNegotiatePort); @@ -111,6 +69,11 @@ network::mojom::HttpAuthDynamicParamsPtr CreateHttpAuthDynamicParams() } // namespace +namespace QtWebEngineCore { + +// The global instance of the SystemNetworkContextmanager. +SystemNetworkContextManager *g_system_network_context_manager = nullptr; + // SharedURLLoaderFactory backed by a SystemNetworkContextManager and its // network context. Transparently handles crashes. class SystemNetworkContextManager::URLLoaderFactoryForSystem : public network::SharedURLLoaderFactory @@ -124,7 +87,6 @@ public: // mojom::URLLoaderFactory implementation: void CreateLoaderAndStart(mojo::PendingReceiver<network::mojom::URLLoader> receiver, - int32_t routing_id, int32_t request_id, uint32_t options, const network::ResourceRequest &url_request, @@ -135,7 +97,7 @@ public: if (!manager_) return; manager_->GetURLLoaderFactory()->CreateLoaderAndStart( - std::move(receiver), routing_id, request_id, options, url_request, + std::move(receiver), request_id, options, url_request, std::move(client), traffic_annotation); } @@ -161,8 +123,6 @@ private: SEQUENCE_CHECKER(sequence_checker_); SystemNetworkContextManager *manager_; - - DISALLOW_COPY_AND_ASSIGN(URLLoaderFactoryForSystem); }; network::mojom::NetworkContext *SystemNetworkContextManager::GetContext() @@ -241,96 +201,159 @@ void SystemNetworkContextManager::OnNetworkServiceCreated(network::mojom::Networ network_service->SetUpHttpAuth(CreateHttpAuthStaticParams()); network_service->ConfigureHttpAuthPrefs(CreateHttpAuthDynamicParams()); - // The system NetworkContext must be created first, since it sets - // |primary_network_context| to true. +#if BUILDFLAG(IS_WIN) + if (content::IsOutOfProcessNetworkService()) + network_service->SetEncryptionKey(OSCrypt::GetRawEncryptionKey()); +#endif + + // Configure the Certificate Transparency logs. + std::vector<std::pair<std::string, base::Time>> disqualified_logs = + certificate_transparency::GetDisqualifiedLogs(); + std::vector<network::mojom::CTLogInfoPtr> log_list_mojo; + for (const auto &ct_log : certificate_transparency::GetKnownLogs()) { + network::mojom::CTLogInfoPtr log_info = network::mojom::CTLogInfo::New(); + log_info->public_key = std::string(ct_log.log_key, ct_log.log_key_length); + log_info->id = crypto::SHA256HashString(log_info->public_key); + log_info->name = ct_log.log_name; + log_info->current_operator = ct_log.current_operator; + + auto it = std::lower_bound( + std::begin(disqualified_logs), std::end(disqualified_logs), log_info->id, + [](const auto& disqualified_log, const std::string& log_id) { + return disqualified_log.first < log_id; + }); + if (it != std::end(disqualified_logs) && it->first == log_info->id) + log_info->disqualified_at = it->second; + + for (size_t i = 0; i < ct_log.previous_operators_length; i++) { + const auto& op = ct_log.previous_operators[i]; + network::mojom::PreviousOperatorEntryPtr previous_operator = + network::mojom::PreviousOperatorEntry::New(); + previous_operator->name = op.name; + previous_operator->end_time = op.end_time; + log_info->previous_operators.push_back(std::move(previous_operator)); + } + + log_list_mojo.push_back(std::move(log_info)); + } + network_service->UpdateCtLogList( + std::move(log_list_mojo), + certificate_transparency::GetLogListTimestamp(), + base::DoNothing()); + + // The system NetworkContext is created first network_service_network_context_.reset(); network_service->CreateNetworkContext( network_service_network_context_.BindNewPipeAndPassReceiver(), CreateNetworkContextParams()); - // Configure the stub resolver. This must be done after the system - // NetworkContext is created, but before anything has the chance to use it. - // bool stub_resolver_enabled; - // base::Optional<std::vector<network::mojom::DnsOverHttpsServerPtr>> dns_over_https_servers; - // GetStubResolverConfig(local_state_, &stub_resolver_enabled, &dns_over_https_servers); - // content::GetNetworkService()->ConfigureStubHostResolver(stub_resolver_enabled, std::move(dns_over_https_servers)); + // Handle --explicitly-allowed-ports + if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kExplicitlyAllowedPorts)) { + std::vector<uint16_t> explicitly_allowed_network_ports; + std::string switch_value = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kExplicitlyAllowedPorts); + const auto split = base::SplitStringPiece(switch_value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + for (const auto &piece : split) { + int port; + if (!base::StringToInt(piece, &port)) + continue; + if (!net::IsPortValid(port)) + continue; + explicitly_allowed_network_ports.push_back(static_cast<uint16_t>(port)); + } + + network_service->SetExplicitlyAllowedPorts(explicitly_allowed_network_ports); + } + + // The network service is a singleton that can be reinstantiated for different reasons, + // e.g., when the network service crashes. Therefore, we configure the stub host + // resolver of the network service here, each time it is instantiated, with our global + // DNS-Over-HTTPS settings. This ensures that the global settings don't get lost + // on reinstantiation and are in effect upon initial instantiation. + QWebEngineGlobalSettingsPrivate::instance()->configureStubHostResolver(); } void SystemNetworkContextManager::AddSSLConfigToNetworkContextParams(network::mojom::NetworkContextParams *network_context_params) { network_context_params->initial_ssl_config = network::mojom::SSLConfig::New(); - network_context_params->initial_ssl_config->rev_checking_enabled = true; network_context_params->initial_ssl_config->symantec_enforcement_disabled = true; } -network::mojom::NetworkContextParamsPtr SystemNetworkContextManager::CreateDefaultNetworkContextParams() +void SystemNetworkContextManager::ConfigureDefaultNetworkContextParams(network::mojom::NetworkContextParams *network_context_params, + cert_verifier::mojom::CertVerifierCreationParams *cert_verifier_creation_params) { - network::mojom::NetworkContextParamsPtr network_context_params = network::mojom::NetworkContextParams::New(); - content::UpdateCorsExemptHeader(network_context_params.get()); - network_context_params->enable_brotli = true; - // network_context_params->user_agent = GetUserAgent(); - // Disable referrers by default. Any consumer that enables referrers should // respect prefs::kEnableReferrers from the appropriate pref store. network_context_params->enable_referrers = false; - // const base::CommandLine& command_line = - // *base::CommandLine::ForCurrentProcess(); - - // // TODO(eroman): Figure out why this doesn't work in single-process mode, - // // or if it does work, now. - // // Should be possible now that a private isolate is used. - // // http://crbug.com/474654 - // if (!command_line.HasSwitch(switches::kWinHttpProxyResolver)) { - // if (command_line.HasSwitch(switches::kSingleProcess)) { - // LOG(ERROR) << "Cannot use V8 Proxy resolver in single process mode."; - // } else { - network_context_params->proxy_resolver_factory = ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver(); - // } - // } - - // network_context_params->pac_quick_check_enabled = local_state_->GetBoolean(prefs::kQuickCheckEnabled); + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + if (!command_line.HasSwitch(switches::kWinHttpProxyResolver)) { + if (command_line.HasSwitch(switches::kSingleProcess)) { + LOG(ERROR) << "Cannot use V8 Proxy resolver in single process mode."; + } else { + network_context_params->proxy_resolver_factory = + ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver(); + } + } +#if BUILDFLAG(IS_WIN) + if (command_line.HasSwitch(switches::kUseSystemProxyResolver)) { + network_context_params->windows_system_proxy_resolver = + ChromeMojoProxyResolverWin::CreateWithSelfOwnedReceiver(); + } +#endif // Use the SystemNetworkContextManager to populate and update SSL // configuration. The SystemNetworkContextManager is owned by the // BrowserProcess itself, so will only be destroyed on shutdown, at which // point, all NetworkContexts will be destroyed as well. - AddSSLConfigToNetworkContextParams(network_context_params.get()); - - // CT is only enabled on Desktop platforms for now. - network_context_params->enforce_chrome_ct_policy = true; - for (const auto &ct_log : certificate_transparency::GetKnownLogs()) { - // TODO(rsleevi): https://crbug.com/702062 - Remove this duplication. - network::mojom::CTLogInfoPtr log_info = network::mojom::CTLogInfo::New(); - log_info->public_key = std::string(ct_log.log_key, ct_log.log_key_length); - log_info->name = ct_log.log_name; - network_context_params->ct_logs.push_back(std::move(log_info)); - } - - return network_context_params; + AddSSLConfigToNetworkContextParams(network_context_params); } network::mojom::NetworkContextParamsPtr SystemNetworkContextManager::CreateNetworkContextParams() { // TODO(mmenke): Set up parameters here (in memory cookie store, etc). - network::mojom::NetworkContextParamsPtr network_context_params = CreateDefaultNetworkContextParams(); - - network_context_params->context_name = std::string("system"); + network::mojom::NetworkContextParamsPtr network_context_params = network::mojom::NetworkContextParams::New(); + cert_verifier::mojom::CertVerifierCreationParamsPtr + cert_verifier_creation_params = cert_verifier::mojom::CertVerifierCreationParams::New(); + ConfigureDefaultNetworkContextParams(network_context_params.get(), cert_verifier_creation_params.get()); network_context_params->enable_referrers = false; network_context_params->http_cache_enabled = false; - // These are needed for PAC scripts that use FTP URLs. -#if !BUILDFLAG(DISABLE_FTP_SUPPORT) - network_context_params->enable_ftp_url_support = true; -#endif - - network_context_params->primary_network_context = false; - proxy_config_monitor_.AddToNetworkContextParams(network_context_params.get()); + network_context_params->cert_verifier_params = + content::GetCertVerifierParams(std::move(cert_verifier_creation_params)); return network_context_params; } + +bool isValidTemplates(std::string templates) +{ + absl::optional<net::DnsOverHttpsConfig> dnsOverHttpsConfig = + net::DnsOverHttpsConfig::FromString(templates); + return dnsOverHttpsConfig.has_value(); +} + + +void configureStubHostResolver(QWebEngineGlobalSettings::SecureDnsMode dnsMode, + std::string dnsOverHttpsTemplates, bool insecureDnsClientEnabled, + bool additionalInsecureDnsTypesEnabled) +{ + if (content::IsNetworkServiceCreated()) { + network::mojom::NetworkService *networkService = content::GetNetworkService(); + if (networkService) { + absl::optional<net::DnsOverHttpsConfig> dohConfig = dnsOverHttpsTemplates.empty() + ? net::DnsOverHttpsConfig() + : net::DnsOverHttpsConfig::FromString(dnsOverHttpsTemplates); + networkService->ConfigureStubHostResolver(insecureDnsClientEnabled, + net::SecureDnsMode(dnsMode), *dohConfig, + additionalInsecureDnsTypesEnabled); + } + } +} + +} // namespace QtWebEngineCore diff --git a/src/core/net/system_network_context_manager.h b/src/core/net/system_network_context_manager.h index 0dd503ce1..d56bdab78 100644 --- a/src/core/net/system_network_context_manager.h +++ b/src/core/net/system_network_context_manager.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // based on chrome/browser/net/system_network_context_manager.h: // Copyright 2017 The Chromium Authors. All rights reserved. @@ -46,20 +10,17 @@ #define SYSTEM_NETWORK_CONTEXT_MANAGER_H_ #include <memory> -#include <string> -#include <vector> -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/optional.h" -#include "services/network/public/mojom/host_resolver.mojom-forward.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/network_service.mojom-forward.h" -#include "services/network/public/mojom/ssl_config.mojom-forward.h" -#include "services/network/public/mojom/url_loader_factory.mojom-forward.h" - +#include "services/network/public/mojom/url_loader_factory.mojom.h" #include "net/proxy_config_monitor.h" +namespace cert_verifier { +namespace mojom { +class CertVerifierCreationParams; +}} + namespace network { namespace mojom { class URLLoaderFactory; @@ -67,9 +28,7 @@ class URLLoaderFactory; class SharedURLLoaderFactory; } // namespace network -namespace net_log { -class NetExportFileWriter; -} +namespace QtWebEngineCore { // Responsible for creating and managing access to the system NetworkContext. // Lives on the UI thread. The NetworkContext this owns is intended for requests @@ -130,8 +89,9 @@ public: // SSL configuration updates. void AddSSLConfigToNetworkContextParams(network::mojom::NetworkContextParams *network_context_params); - // Returns default set of parameters for configuring the network service. - network::mojom::NetworkContextParamsPtr CreateDefaultNetworkContextParams(); + // Configures the default set of parameters for the network context. + void ConfigureDefaultNetworkContextParams(network::mojom::NetworkContextParams *, + cert_verifier::mojom::CertVerifierCreationParams *); private: class URLLoaderFactoryForSystem; @@ -154,8 +114,8 @@ private: mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory_; ProxyConfigMonitor proxy_config_monitor_; - - DISALLOW_COPY_AND_ASSIGN(SystemNetworkContextManager); }; +} // namespace QtWebEngineCore + #endif // SYSTEM_NETWORK_CONTEXT_MANAGER_H_ diff --git a/src/core/net/url_request_custom_job_delegate.cpp b/src/core/net/url_request_custom_job_delegate.cpp index ff307bede..fb6b605a4 100644 --- a/src/core/net/url_request_custom_job_delegate.cpp +++ b/src/core/net/url_request_custom_job_delegate.cpp @@ -1,46 +1,9 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "url_request_custom_job_delegate.h" #include "url_request_custom_job_proxy.h" -#include "base/task/post_task.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "net/base/net_errors.h" @@ -51,16 +14,16 @@ namespace QtWebEngineCore { -URLRequestCustomJobDelegate::URLRequestCustomJobDelegate(URLRequestCustomJobProxy *proxy, - const QUrl &url, - const QByteArray &method, - const QUrl &initiatorOrigin, - const QMap<QByteArray, QByteArray> &headers) - : m_proxy(proxy), - m_request(url), - m_method(method), - m_initiatorOrigin(initiatorOrigin), - m_requestHeaders(headers) +URLRequestCustomJobDelegate::URLRequestCustomJobDelegate( + URLRequestCustomJobProxy *proxy, const QUrl &url, const QByteArray &method, + const QUrl &initiatorOrigin, const QMap<QByteArray, QByteArray> &headers, + network::ResourceRequestBody *requestBody) + : m_proxy(proxy) + , m_request(url) + , m_method(method) + , m_initiatorOrigin(initiatorOrigin) + , m_requestHeaders(headers) + , m_resourceRequestBody(ResourceRequestBody(requestBody)) { } @@ -88,13 +51,29 @@ QMap<QByteArray, QByteArray> URLRequestCustomJobDelegate::requestHeaders() const return m_requestHeaders; } +QIODevice *URLRequestCustomJobDelegate::requestBody() +{ + return &m_resourceRequestBody; +} + +void URLRequestCustomJobDelegate::setAdditionalResponseHeaders( + const QMultiMap<QByteArray, QByteArray> &additionalResponseHeaders) +{ + m_additionalResponseHeaders = additionalResponseHeaders; +} + void URLRequestCustomJobDelegate::reply(const QByteArray &contentType, QIODevice *device) { - if (device) + if (!device) + m_proxy->m_ioTaskRunner->PostTask(FROM_HERE, + base::BindOnce(&URLRequestCustomJobProxy::succeed, m_proxy)); + else { QObject::connect(device, &QIODevice::readyRead, this, &URLRequestCustomJobDelegate::slotReadyRead); - m_proxy->m_ioTaskRunner->PostTask(FROM_HERE, - base::BindOnce(&URLRequestCustomJobProxy::reply, - m_proxy, contentType.toStdString(),device)); + m_proxy->m_ioTaskRunner->PostTask(FROM_HERE, + base::BindOnce(&URLRequestCustomJobProxy::reply, m_proxy, + contentType.toStdString(), device, + std::move(m_additionalResponseHeaders))); + } } void URLRequestCustomJobDelegate::slotReadyRead() diff --git a/src/core/net/url_request_custom_job_delegate.h b/src/core/net/url_request_custom_job_delegate.h index 93ae39e84..63db46464 100644 --- a/src/core/net/url_request_custom_job_delegate.h +++ b/src/core/net/url_request_custom_job_delegate.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // // W A R N I N G @@ -53,6 +17,7 @@ #include "base/memory/ref_counted.h" #include "qtwebenginecoreglobal_p.h" +#include "resource_request_body_qt.h" #include <QMap> #include <QObject> @@ -60,11 +25,15 @@ QT_FORWARD_DECLARE_CLASS(QIODevice) +namespace network { +class ResourceRequestBody; +} + namespace QtWebEngineCore { class URLRequestCustomJobProxy; -class Q_WEBENGINECORE_PRIVATE_EXPORT URLRequestCustomJobDelegate : public QObject +class Q_WEBENGINECORE_EXPORT URLRequestCustomJobDelegate : public QObject { Q_OBJECT public: @@ -83,7 +52,10 @@ public: QByteArray method() const; QUrl initiator() const; QMap<QByteArray, QByteArray> requestHeaders() const; + QIODevice *requestBody(); + void + setAdditionalResponseHeaders(const QMultiMap<QByteArray, QByteArray> &additionalResponseHeaders); void reply(const QByteArray &contentType, QIODevice *device); void redirect(const QUrl &url); void abort(); @@ -93,11 +65,10 @@ private Q_SLOTS: void slotReadyRead(); private: - URLRequestCustomJobDelegate(URLRequestCustomJobProxy *proxy, - const QUrl &url, - const QByteArray &method, - const QUrl &initiatorOrigin, - const QMap<QByteArray, QByteArray> &requestHeaders); + URLRequestCustomJobDelegate(URLRequestCustomJobProxy *proxy, const QUrl &url, + const QByteArray &method, const QUrl &initiatorOrigin, + const QMap<QByteArray, QByteArray> &requestHeaders, + network::ResourceRequestBody *requestBody); friend class URLRequestCustomJobProxy; scoped_refptr<URLRequestCustomJobProxy> m_proxy; @@ -105,6 +76,8 @@ private: QByteArray m_method; QUrl m_initiatorOrigin; const QMap<QByteArray, QByteArray> m_requestHeaders; + QMultiMap<QByteArray, QByteArray> m_additionalResponseHeaders; + ResourceRequestBody m_resourceRequestBody; }; } // namespace diff --git a/src/core/net/url_request_custom_job_proxy.cpp b/src/core/net/url_request_custom_job_proxy.cpp index f734db645..54faddc62 100644 --- a/src/core/net/url_request_custom_job_proxy.cpp +++ b/src/core/net/url_request_custom_job_proxy.cpp @@ -1,47 +1,12 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2017 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "url_request_custom_job_proxy.h" #include "url_request_custom_job_delegate.h" #include "content/public/browser/browser_thread.h" #include "net/base/net_errors.h" +#include "services/network/public/cpp/resource_request_body.h" #include "api/qwebengineurlrequestjob.h" #include "profile_adapter.h" @@ -76,27 +41,30 @@ void URLRequestCustomJobProxy::release() } } -// Fix me: this is never used -/* -void URLRequestCustomJobProxy::setReplyCharset(const std::string &charset) -{ - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - if (!m_job) - return; - m_job->m_charset = charset; -} -*/ -void URLRequestCustomJobProxy::reply(std::string mimeType, QIODevice *device) +void URLRequestCustomJobProxy::reply(std::string contentType, QIODevice *device, + QMultiMap<QByteArray, QByteArray> additionalResponseHeaders) { if (!m_client) return; DCHECK (!m_ioTaskRunner || m_ioTaskRunner->RunsTasksInCurrentSequence()); - m_client->m_mimeType = mimeType; + QByteArray qcontentType = QByteArray::fromStdString(contentType).toLower(); + const int sidx = qcontentType.indexOf(';'); + if (sidx > 0) { + const int cidx = qcontentType.indexOf("charset=", sidx); + if (cidx > 0) { + m_client->m_charset = qcontentType.mid(cidx + 8).trimmed().toStdString(); + qcontentType = qcontentType.first(sidx); + } else { + qWarning() << "QWebEngineUrlRequestJob::reply(): Unrecognized content-type format with ';'" << qcontentType; + } + } + m_client->m_mimeType = qcontentType.trimmed().toStdString(); m_client->m_device = device; + m_client->m_additionalResponseHeaders = std::move(additionalResponseHeaders); if (m_client->m_device && !m_client->m_device->isReadable()) m_client->m_device->open(QIODevice::ReadOnly); - if (m_client->m_firstBytePosition > 0) + if (m_client->m_device && m_client->m_firstBytePosition > 0) m_client->m_device->seek(m_client->m_firstBytePosition); qint64 deviceSize = m_client->m_device ? m_client->m_device->size() : -1; @@ -150,6 +118,11 @@ void URLRequestCustomJobProxy::fail(int error) // else we fail on the next read, or the read that might already be in progress } +void URLRequestCustomJobProxy::succeed() +{ + m_client->notifySuccess(); +} + void URLRequestCustomJobProxy::readyRead() { DCHECK (m_ioTaskRunner->RunsTasksInCurrentSequence()); @@ -158,8 +131,9 @@ void URLRequestCustomJobProxy::readyRead() } void URLRequestCustomJobProxy::initialize(GURL url, std::string method, - base::Optional<url::Origin> initiator, - std::map<std::string, std::string> headers) + absl::optional<url::Origin> initiator, + std::map<std::string, std::string> headers, + scoped_refptr<network::ResourceRequestBody> requestBody) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); Q_ASSERT(!m_delegate); @@ -177,10 +151,9 @@ void URLRequestCustomJobProxy::initialize(GURL url, std::string method, qHeaders.insert(toQByteArray(it->first), toQByteArray(it->second)); if (schemeHandler) { - m_delegate = new URLRequestCustomJobDelegate(this, toQt(url), - QByteArray::fromStdString(method), - initiatorOrigin, - qHeaders); + m_delegate = + new URLRequestCustomJobDelegate(this, toQt(url), QByteArray::fromStdString(method), + initiatorOrigin, qHeaders, requestBody.get()); QWebEngineUrlRequestJob *requestJob = new QWebEngineUrlRequestJob(m_delegate); schemeHandler->requestStarted(requestJob); } diff --git a/src/core/net/url_request_custom_job_proxy.h b/src/core/net/url_request_custom_job_proxy.h index b14322f91..c03992411 100644 --- a/src/core/net/url_request_custom_job_proxy.h +++ b/src/core/net/url_request_custom_job_proxy.h @@ -1,54 +1,23 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2017 Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef URL_REQUEST_CUSTOM_JOB_PROXY_H_ #define URL_REQUEST_CUSTOM_JOB_PROXY_H_ -#include "base/memory/weak_ptr.h" -#include "base/optional.h" -#include "base/sequenced_task_runner.h" +#include "base/task/sequenced_task_runner.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" #include "url/origin.h" #include <QtCore/QPointer> +#include <QMap> +#include <QByteArray> QT_FORWARD_DECLARE_CLASS(QIODevice) +namespace network { +class ResourceRequestBody; +} + namespace QtWebEngineCore { class URLRequestCustomJob; @@ -65,6 +34,7 @@ public: public: std::string m_mimeType; std::string m_charset; + QMultiMap<QByteArray, QByteArray> m_additionalResponseHeaders; GURL m_redirect; QIODevice *m_device; int64_t m_firstBytePosition; @@ -74,6 +44,7 @@ public: virtual void notifyCanceled() = 0; virtual void notifyAborted() = 0; virtual void notifyStartFailure(int) = 0; + virtual void notifySuccess() = 0; virtual void notifyReadyRead() = 0; virtual base::SequencedTaskRunner *taskRunner() = 0; }; @@ -85,12 +56,16 @@ public: // Called from URLRequestCustomJobDelegate via post: //void setReplyCharset(const std::string &); - void reply(std::string mimeType, QIODevice *device); + void reply(std::string mimeType, QIODevice *device, + QMultiMap<QByteArray, QByteArray> additionalResponseHeaders); void redirect(GURL url); void abort(); void fail(int error); + void succeed(); void release(); - void initialize(GURL url, std::string method, base::Optional<url::Origin> initiatorOrigin, std::map<std::string, std::string> headers); + void initialize(GURL url, std::string method, absl::optional<url::Origin> initiatorOrigin, + std::map<std::string, std::string> headers, + scoped_refptr<network::ResourceRequestBody> requestBody); void readyRead(); // IO thread owned: diff --git a/src/core/net/version_ui_qt.cpp b/src/core/net/version_ui_qt.cpp new file mode 100644 index 000000000..61a89596a --- /dev/null +++ b/src/core/net/version_ui_qt.cpp @@ -0,0 +1,56 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "version_ui_qt.h" +#include "api/qtwebenginecoreglobal.h" +#include "build/build_config.h" +#include "base/command_line.h" +#include "chrome/common/url_constants.h" +#include "chrome/browser/profiles/profile.h" +#include "qtwebengine/grit/qt_webengine_resources.h" +#include "services/network/public/cpp/content_security_policy/content_security_policy.h" + +namespace { +const char kQtWebEngineVersion[] = "qtwebengine_version"; +const char kQtWebEngineChromiumVersion[] = "qtwebengine_chromium_version"; +const char kQtWebEngineChromiumSecurityPatchVersion[] = + "qtwebengine_chromium_security_patch_version"; +const char kCommandLine[] = "command_line"; +const char kQtVersionCSS[] = "qt_version.css"; +const char kQtLogo[] = "images/qt.png"; +const char kQtWebEngineLogo[] = "images/qtwebengine.png"; +} + +VersionUIQt::VersionUIQt(content::WebUI *web_ui) : content::WebUIController(web_ui) +{ + + Profile *profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource *html_source = + content::WebUIDataSource::CreateAndAdd(profile, chrome::kChromeUIVersionQtHost); + html_source->OverrideContentSecurityPolicy( + network::mojom::CSPDirectiveName::ScriptSrc, + "script-src chrome://resources 'self' 'unsafe-inline';"); + html_source->SetDefaultResource(IDR_VERSION_UI_QT_HTML); + html_source->AddResourcePath(kQtVersionCSS, IDR_VERSION_UI_QT_CSS); + html_source->AddResourcePath(kQtLogo, IDR_QT_LOGO); + html_source->AddResourcePath(kQtWebEngineLogo, IDR_QTWEBENGINE_LOGO); + + html_source->AddString(kQtWebEngineVersion, qWebEngineVersion()); + html_source->AddString(kQtWebEngineChromiumVersion, qWebEngineChromiumVersion()); + html_source->AddString(kQtWebEngineChromiumSecurityPatchVersion, + qWebEngineChromiumSecurityPatchVersion()); +#if BUILDFLAG(IS_WIN) + html_source->AddString( + kCommandLine, + base::AsString16(base::CommandLine::ForCurrentProcess()->GetCommandLineString())); +#else + std::string command_line; + typedef std::vector<std::string> ArgvList; + const ArgvList &argv = base::CommandLine::ForCurrentProcess()->argv(); + for (auto iter = argv.begin(); iter != argv.end(); iter++) + command_line += " " + *iter; + html_source->AddString(kCommandLine, command_line); +#endif +} + +VersionUIQt::~VersionUIQt() { } diff --git a/src/core/net/version_ui_qt.h b/src/core/net/version_ui_qt.h new file mode 100644 index 000000000..1fe8ef9e0 --- /dev/null +++ b/src/core/net/version_ui_qt.h @@ -0,0 +1,32 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#ifndef VERSION_UI_QT_H_ +#define VERSION_UI_QT_H_ + +#include "build/build_config.h" +#include "content/public/browser/web_ui_controller.h" +#include "content/public/browser/web_ui_data_source.h" + +class VersionUIQt : public content::WebUIController +{ +public: + explicit VersionUIQt(content::WebUI *web_ui); + ~VersionUIQt() override; + + VersionUIQt(const VersionUIQt &) = delete; + VersionUIQt &operator=(const VersionUIQt &) = delete; +}; + +#endif // VERSION_UI_QT_H diff --git a/src/core/net/webui_controller_factory_qt.cpp b/src/core/net/webui_controller_factory_qt.cpp index 27e58d75f..ed35a3e36 100644 --- a/src/core/net/webui_controller_factory_qt.cpp +++ b/src/core/net/webui_controller_factory_qt.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2017 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only // Based on chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc: // Copyright (c) 2012 The Chromium Authors. All rights reserved. @@ -44,39 +8,37 @@ #include "webui_controller_factory_qt.h" -#include "base/bind.h" -#include "base/location.h" -#include "base/threading/thread_task_runner_handle.h" +#include "build_config_qt.h" +#include "devtools_frontend_qt.h" +#include "base/functional/bind.h" #include "build/build_config.h" #include "chrome/browser/accessibility/accessibility_ui.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/device_log_ui.h" #include "chrome/browser/ui/webui/devtools_ui.h" -#include "chrome/browser/ui/webui/quota_internals/quota_internals_ui.h" +#include "chrome/browser/ui/webui/net_internals/net_internals_ui.h" +#include "chrome/browser/ui/webui/user_actions/user_actions_ui.h" #include "chrome/common/url_constants.h" -#include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" -#include "content/public/common/content_client.h" #include "content/public/common/url_utils.h" #include "extensions/buildflags/buildflags.h" #include "media/media_buildflags.h" -#include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" -#include "ui/web_dialogs/web_dialog_ui.h" #include "url/gurl.h" +#include "version_ui_qt.h" -#if defined(OS_LINUX) || defined(OS_ANDROID) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) #include "chrome/browser/ui/webui/sandbox/sandbox_internals_ui.h" #endif +#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions) +#include "chrome/browser/ui/webui/media/webrtc_logs_ui.h" +#endif + // The Following WebUIs are disabled because they currently doesn't build // or doesn't work, but would be interesting for us if they did: // #include "chrome/browser/ui/webui/inspect_ui.h" -// #include "chrome/browser/ui/webui/user_actions/user_actions_ui.h" - -// #if BUILDFLAG(ENABLE_WEBRTC) -// #include "chrome/browser/ui/webui/media/webrtc_logs_ui.h" -// #endif // #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h" @@ -119,26 +81,35 @@ std::unique_ptr<WebUIController> NewWebUI(WebUI *web_ui, const GURL & /*url*/) // with it. WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, const GURL &url) { + Q_UNUSED(web_ui); + Q_UNUSED(profile); // This will get called a lot to check all URLs, so do a quick check of other // schemes to filter out most URLs. if (!content::HasWebUIScheme(url)) - return NULL; + return nullptr; // We must compare hosts only since some of the Web UIs append extra stuff // after the host name. - if (url.host() == chrome::kChromeUIQuotaInternalsHost) - return &NewWebUI<QuotaInternalsUI>; + if (url.host_piece() == chrome::kChromeUINetInternalsHost) + return &NewWebUI<NetInternalsUI>; if (url.SchemeIs(content::kChromeDevToolsScheme)) { - // if (!DevToolsUIBindings::IsValidFrontendURL(url)) - // return nullptr; + if (!QtWebEngineCore::DevToolsFrontendQt::IsValidFrontendURL(url)) + return nullptr; return &NewWebUI<DevToolsUI>; } - if (url.host() == chrome::kChromeUIAccessibilityHost) + if (url.host_piece() == chrome::kChromeUIAccessibilityHost) return &NewWebUI<AccessibilityUI>; -// if (url.host_piece() == chrome::kChromeUIUserActionsHost) -// return &NewWebUI<UserActionsUI>; + if (url.host_piece() == chrome::kChromeUIUserActionsHost) + return &NewWebUI<UserActionsUI>; + + if (url.host_piece() == chrome::kChromeUIDeviceLogHost) + return &NewWebUI<chromeos::DeviceLogUI>; + + if (url.host_piece() == chrome::kChromeUIVersionQtHost) + return &NewWebUI<VersionUIQt>; + // if (url.host_piece() == chrome::kChromeUIInspectHost) // return &NewWebUI<InspectUI>; // @@ -150,21 +121,17 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, co // if (url.host_piece() == chrome::kChromeUIExtensionsFrameHost) // return &NewWebUI<extensions::ExtensionsUI>; //#endif -//#if BUILDFLAG(ENABLE_PLUGINS) -// if (url.host_piece() == chrome::kChromeUIFlashHost) -// return &NewWebUI<FlashUI>; -//#endif //#if BUILDFLAG(ENABLE_PRINT_PREVIEW) // if (url.host_piece() == chrome::kChromeUIPrintHost && // !profile->GetPrefs()->GetBoolean(prefs::kPrintPreviewDisabled)) { // return &NewWebUI<PrintPreviewUI>; // } //#endif -//#if BUILDFLAG(ENABLE_WEBRTC) -// if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) -// return &NewWebUI<WebRtcLogsUI>; -//#endif -#if defined(OS_LINUX) || defined(OS_ANDROID) +#if QT_CONFIG(webengine_webrtc) && QT_CONFIG(webengine_extensions) + if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) + return &NewWebUI<WebRtcLogsUI>; +#endif +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) if (url.host_piece() == chrome::kChromeUISandboxHost) return &NewWebUI<SandboxInternalsUI>; #endif @@ -187,11 +154,6 @@ bool WebUIControllerFactoryQt::UseWebUIForURL(content::BrowserContext *browser_c return GetWebUIType(browser_context, url) != WebUI::kNoWebUI; } -bool WebUIControllerFactoryQt::UseWebUIBindingsForURL(content::BrowserContext *browser_context, const GURL &url) -{ - return UseWebUIForURL(browser_context, url); -} - std::unique_ptr<WebUIController> WebUIControllerFactoryQt::CreateWebUIControllerForURL(WebUI *web_ui, const GURL &url) { Profile *profile = Profile::FromWebUI(web_ui); diff --git a/src/core/net/webui_controller_factory_qt.h b/src/core/net/webui_controller_factory_qt.h index 1cc76349b..22219dd5a 100644 --- a/src/core/net/webui_controller_factory_qt.h +++ b/src/core/net/webui_controller_factory_qt.h @@ -1,57 +1,12 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtWebEngine 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 The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/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 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2017 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef WEB_UI_CONTROLLER_FACTORY_QT_H_ #define WEB_UI_CONTROLLER_FACTORY_QT_H_ -#include "base/macros.h" #include "base/memory/singleton.h" -#include "components/favicon_base/favicon_callback.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_controller_factory.h" -#include "ui/base/layout.h" - -class Profile; - -namespace base { -class RefCountedMemory; -} namespace QtWebEngineCore { @@ -60,7 +15,6 @@ class WebUIControllerFactoryQt : public content::WebUIControllerFactory public: content::WebUI::TypeID GetWebUIType(content::BrowserContext *browserContext, const GURL &url) override; bool UseWebUIForURL(content::BrowserContext *browserContext, const GURL &url) override; - bool UseWebUIBindingsForURL(content::BrowserContext *browserContext, const GURL &url) override; std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(content::WebUI *webUi, const GURL &url) override; static WebUIControllerFactoryQt *GetInstance(); @@ -71,8 +25,6 @@ protected: private: friend struct base::DefaultSingletonTraits<WebUIControllerFactoryQt>; - - DISALLOW_COPY_AND_ASSIGN(WebUIControllerFactoryQt); }; } // namespace QtWebEngineCore |