diff options
Diffstat (limited to 'src/core/net')
28 files changed, 854 insertions, 266 deletions
diff --git a/src/core/net/client_cert_override.cpp b/src/core/net/client_cert_qt.cpp index 875918c57..044e5618e 100644 --- a/src/core/net/client_cert_override.cpp +++ b/src/core/net/client_cert_qt.cpp @@ -1,12 +1,13 @@ // 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_override.h" +#include "client_cert_qt.h" -#include "base/bind.h" -#include "base/task/post_task.h" -#include "base/callback_forward.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" @@ -16,43 +17,35 @@ #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) +#if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #endif -#if defined(OS_WIN) +#if defined(Q_OS_WIN) #include "net/ssl/client_cert_store_win.h" #endif -#if defined(OS_MAC) +#if BUILDFLAG(IS_MAC) #include "net/ssl/client_cert_store_mac.h" #endif namespace { -class ClientCertIdentityOverride : public net::ClientCertIdentity +class ClientCertIdentityQt : public net::ClientCertIdentity { public: - ClientCertIdentityOverride(scoped_refptr<net::X509Certificate> cert, scoped_refptr<net::SSLPrivateKey> key) + ClientCertIdentityQt(scoped_refptr<net::X509Certificate> cert, scoped_refptr<net::SSLPrivateKey> key) : net::ClientCertIdentity(std::move(cert)), m_key(std::move(key)) {} - ~ClientCertIdentityOverride() override = default; + ~ClientCertIdentityQt() 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_MAC) - SecIdentityRef sec_identity_ref() const override - { - return nullptr; - } -#endif - private: scoped_refptr<net::SSLPrivateKey> m_key; }; @@ -61,55 +54,74 @@ private: namespace QtWebEngineCore { -ClientCertOverrideStore::ClientCertOverrideStore(ClientCertificateStoreData *storeData) +ClientCertStoreQt::ClientCertStoreQt(ClientCertificateStoreData *storeData) : ClientCertStore() , m_storeData(storeData) , m_nativeStore(createNativeStore()) { } -ClientCertOverrideStore::~ClientCertOverrideStore() = default; +ClientCertStoreQt::~ClientCertStoreQt() = default; #if QT_CONFIG(ssl) -net::ClientCertIdentityList ClientCertOverrideStore::GetClientCertsOnUIThread(const net::SSLCertRequestInfo &cert_request_info) +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 != 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; + 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 net::ClientCertIdentityList(); + return selected_identities; } -void ClientCertOverrideStore::GetClientCertsReturn(const net::SSLCertRequestInfo &cert_request_info, +void ClientCertStoreQt::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 + // 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 ClientCertOverrideStore::GetClientCerts(const net::SSLCertRequestInfo &cert_request_info, +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 = base::PostTaskAndReplyWithResult( - FROM_HERE, { content::BrowserThread::UI }, - base::BindOnce(&ClientCertOverrideStore::GetClientCertsOnUIThread, + bool ok = content::GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&ClientCertStoreQt::GetClientCertsOnUIThread, base::Unretained(this), std::cref(cert_request_info)), - base::BindOnce(&ClientCertOverrideStore::GetClientCertsReturn, + 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 @@ -121,13 +133,13 @@ void ClientCertOverrideStore::GetClientCerts(const net::SSLCertRequestInfo &cert } // static -std::unique_ptr<net::ClientCertStore> ClientCertOverrideStore::createNativeStore() +std::unique_ptr<net::ClientCertStore> ClientCertStoreQt::createNativeStore() { -#if defined(USE_NSS_CERTS) +#if BUILDFLAG(USE_NSS_CERTS) return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(net::ClientCertStoreNSS::PasswordDelegateFactory())); -#elif defined(OS_WIN) +#elif defined(Q_OS_WIN) return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin()); -#elif defined(OS_MAC) +#elif BUILDFLAG(IS_MAC) return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac()); #else return nullptr; diff --git a/src/core/net/client_cert_override.h b/src/core/net/client_cert_qt.h index 6f740cc9c..96579fae6 100644 --- a/src/core/net/client_cert_override.h +++ b/src/core/net/client_cert_qt.h @@ -1,12 +1,12 @@ // 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_OVERRIDE_P_H -#define CLIENT_CERT_OVERRIDE_P_H +#ifndef CLIENT_CERT_QT_P_H +#define CLIENT_CERT_QT_P_H -#include "net/ssl/client_cert_store.h" -#include "base/callback_forward.h" +#include "base/functional/callback_forward.h" #include "net/cert/x509_certificate.h" +#include "net/ssl/client_cert_store.h" namespace net { class SSLCertRequestInfo; @@ -15,11 +15,11 @@ class SSLCertRequestInfo; namespace QtWebEngineCore { struct ClientCertificateStoreData; -class ClientCertOverrideStore : public net::ClientCertStore +class ClientCertStoreQt : public net::ClientCertStore { public: - ClientCertOverrideStore(ClientCertificateStoreData *storeData); - virtual ~ClientCertOverrideStore() override; + ClientCertStoreQt(ClientCertificateStoreData *storeData); + virtual ~ClientCertStoreQt() override; void GetClientCerts(const net::SSLCertRequestInfo &cert_request_info, ClientCertListCallback callback) override; private: diff --git a/src/core/net/client_cert_store_data.cpp b/src/core/net/client_cert_store_data.cpp index 75c35ecc1..0de6885df 100644 --- a/src/core/net/client_cert_store_data.cpp +++ b/src/core/net/client_cert_store_data.cpp @@ -20,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); @@ -65,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"; @@ -82,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()); } @@ -97,7 +97,8 @@ void ClientCertificateStoreData::add(const QSslCertificate &certificate, const Q Entry *data = new Entry; data->keyPtr = wrapOpenSSLPrivateKey(sslKeyInBytes); - data->certPtr = net::X509Certificate::CreateFromBytes(base::make_span((const unsigned char *)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/cookie_monster_delegate_qt.cpp b/src/core/net/cookie_monster_delegate_qt.cpp index 0f82a4d1f..d107c520c 100644 --- a/src/core/net/cookie_monster_delegate_qt.cpp +++ b/src/core/net/cookie_monster_delegate_qt.cpp @@ -3,7 +3,7 @@ #include "cookie_monster_delegate_qt.h" -#include "base/bind.h" +#include "base/functional/bind.h" #include "net/cookies/cookie_util.h" #include "services/network/public/mojom/cookie_manager.mojom.h" @@ -97,8 +97,9 @@ void CookieMonsterDelegateQt::setCookie(const QNetworkCookie &cookie, const QUrl std::string cookie_line = cookie.toRawForm().toStdString(); net::CookieInclusionStatus inclusion; - auto canonCookie = net::CanonicalCookie::Create(gurl, cookie_line, base::Time::Now(), absl::nullopt, absl::nullopt, &inclusion); - if (!inclusion.IsInclude()) { + 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; } @@ -140,7 +141,7 @@ void CookieMonsterDelegateQt::deleteAllCookies() 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(); diff --git a/src/core/net/cookie_monster_delegate_qt.h b/src/core/net/cookie_monster_delegate_qt.h index d84946bb9..f6872323d 100644 --- a/src/core/net/cookie_monster_delegate_qt.h +++ b/src/core/net/cookie_monster_delegate_qt.h @@ -24,6 +24,7 @@ #endif #include "base/memory/ref_counted.h" #include "mojo/public/cpp/bindings/receiver.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" @@ -41,12 +42,12 @@ 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; @@ -65,7 +66,7 @@ public: 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); diff --git a/src/core/net/custom_url_loader_factory.cpp b/src/core/net/custom_url_loader_factory.cpp index a41ece61b..4274def99 100644 --- a/src/core/net/custom_url_loader_factory.cpp +++ b/src/core/net/custom_url_loader_factory.cpp @@ -4,7 +4,6 @@ #include "custom_url_loader_factory.h" #include "base/strings/stringprintf.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/pending_receiver.h" @@ -33,6 +32,7 @@ #include <QtCore/qiodevice.h> #include <QtCore/qmimedatabase.h> #include <QtCore/qmimedata.h> +#include <QtCore/qpointer.h> #include <QtCore/qurl.h> namespace QtWebEngineCore { @@ -44,13 +44,13 @@ class CustomURLLoader : public network::mojom::URLLoader { public: static void CreateAndStart(const network::ResourceRequest &request, - network::mojom::URLLoaderRequest loader, - network::mojom::URLLoaderClientPtrInfo client_info, + mojo::PendingReceiver<network::mojom::URLLoader> loader, + mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote, QPointer<ProfileAdapter> profileAdapter) { // 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); customUrlLoader->Start(); } @@ -64,7 +64,7 @@ public: 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) @@ -83,14 +83,14 @@ public: private: CustomURLLoader(const network::ResourceRequest &request, - network::mojom::URLLoaderRequest loader, - network::mojom::URLLoaderClientPtrInfo client_info, + mojo::PendingReceiver<network::mojom::URLLoader> loader, + mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote, QPointer<ProfileAdapter> profileAdapter) // ### 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_receiver(this, std::move(loader)) - , m_client(std::move(client_info)) + , m_client(std::move(client_remote)) , m_request(request) { DCHECK(m_taskRunner->RunsTasksInCurrentSequence()); @@ -151,9 +151,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) @@ -204,7 +206,7 @@ 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_receiver.is_bound()) delete this; @@ -263,11 +265,17 @@ 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; + 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; @@ -286,19 +294,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_pipeConsumerHandle)); + 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); + 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 { @@ -337,8 +343,9 @@ 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 notifyReadyRead() override @@ -366,8 +373,10 @@ private: uint32_t bufferSize = 0; 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()}) @@ -379,13 +388,20 @@ private: 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; } @@ -418,7 +434,7 @@ private: scoped_refptr<URLRequestCustomJobProxy> m_proxy; mojo::Receiver<network::mojom::URLLoader> m_receiver; - network::mojom::URLLoaderClientPtr m_client; + mojo::Remote<network::mojom::URLLoaderClient> m_client; mojo::ScopedDataPipeProducerHandle m_pipeProducerHandle; mojo::ScopedDataPipeConsumerHandle m_pipeConsumerHandle; std::unique_ptr<mojo::SimpleWatcher> m_watcher; @@ -439,7 +455,7 @@ private: class CustomURLLoaderFactory : public network::mojom::URLLoaderFactory { public: CustomURLLoaderFactory(ProfileAdapter *profileAdapter, mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) - : m_taskRunner(base::CreateSequencedTaskRunner({ content::BrowserThread::IO })) + : m_taskRunner(content::GetIOThreadTaskRunner({})) , m_profileAdapter(profileAdapter) { m_receivers.set_disconnect_handler(base::BindRepeating( 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 e0e9bc80a..159fa28ca 100644 --- a/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp +++ b/src/core/net/plugin_response_interceptor_url_loader_throttle.cpp @@ -8,9 +8,8 @@ #include "plugin_response_interceptor_url_loader_throttle.h" -#include "base/bind.h" -#include "base/guid.h" -#include "base/task/post_task.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" @@ -28,6 +27,51 @@ #include "web_engine_settings.h" #include <string> +#include <tuple> + +namespace { +void ClearAllButFrameAncestors(network::mojom::URLResponseHead *response_head) +{ + response_head->headers->RemoveHeader("Content-Security-Policy"); + response_head->headers->RemoveHeader("Content-Security-Policy-Report-Only"); + + if (!response_head->parsed_headers) + 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)); + } + + csp.swap(cleared); +} +} // namespace + namespace QtWebEngineCore { @@ -42,13 +86,16 @@ void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL bool *defer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (content::download_utils::MustDownload(response_url, response_head->headers.get(), response_head->mime_type)) - return; content::WebContents *web_contents = content::WebContents::FromFrameTreeNodeId(m_frame_tree_node_id); if (!web_contents) return; + if (content::download_utils::MustDownload( + web_contents->GetBrowserContext(), + response_url, response_head->headers.get(), response_head->mime_type)) + return; + std::string extension_id; if (response_head->mime_type == "application/pdf") extension_id = extension_misc::kPdfExtensionId; @@ -72,16 +119,16 @@ void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL // 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) - response_head->headers->RemoveHeader("Content-Security-Policy"); + ClearAllButFrameAncestors(response_head); MimeTypesHandler::ReportUsedHandler(extension_id); - std::string view_id = base::GenerateGUID(); + 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; - ignore_result(dummy_new_loader.InitWithNewPipeAndPassReceiver()); + std::ignore = dummy_new_loader.InitWithNewPipeAndPassReceiver(); mojo::Remote<network::mojom::URLLoaderClient> new_client; mojo::PendingReceiver<network::mojom::URLLoaderClient> new_client_receiver = new_client.BindNewPipeAndPassReceiver(); @@ -106,18 +153,17 @@ void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL producer_handle->WriteData( payload.c_str(), &len, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); - - new_client->OnStartLoadingResponseBody(std::move(consumer_handle)); - 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); + 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(); @@ -130,11 +176,12 @@ void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL auto transferrable_loader = blink::mojom::TransferrableURLLoader::New(); transferrable_loader->url = GURL( extensions::Extension::GetBaseURLFromExtensionId(extension_id).spec() + - base::GenerateGUID()); + 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; @@ -143,7 +190,6 @@ void PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse(const GURL base::BindOnce( &extensions::StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent, extension_id, view_id, embedded, m_frame_tree_node_id, - -1 /* render_process_id */, -1 /* render_frame_id */, std::move(transferrable_loader), response_url)); } diff --git a/src/core/net/proxy_config_monitor.cpp b/src/core/net/proxy_config_monitor.cpp index d4543947a..8315b7bf2 100644 --- a/src/core/net/proxy_config_monitor.cpp +++ b/src/core/net/proxy_config_monitor.cpp @@ -10,14 +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/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> @@ -28,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 69655b807..585e4b7ed 100644 --- a/src/core/net/proxy_config_monitor.h +++ b/src/core/net/proxy_config_monitor.h @@ -10,16 +10,11 @@ #define PROXY_CONFIG_MONITOR_H #include <memory> -#include <string> -#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 { @@ -61,4 +56,4 @@ private: mojo::RemoteSet<network::mojom::ProxyConfigClient> proxy_config_client_set_; }; -#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 14514a615..fcce08550 100644 --- a/src/core/net/proxy_config_service_qt.cpp +++ b/src/core/net/proxy_config_service_qt.cpp @@ -9,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()); @@ -36,7 +35,7 @@ net::ProxyServer ProxyConfigServiceQt::fromQNetworkProxy(const QNetworkProxy &qt ProxyConfigServiceQt::ProxyConfigServiceQt(PrefService *prefService, const scoped_refptr<base::SequencedTaskRunner> &taskRunner) - : m_baseService(net::ConfiguredProxyResolutionService::CreateSystemProxyConfigService(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 dcbc5074f..49c9877a5 100644 --- a/src/core/net/proxy_config_service_qt.h +++ b/src/core/net/proxy_config_service_qt.h @@ -4,10 +4,8 @@ #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/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" diff --git a/src/core/net/proxying_restricted_cookie_manager_qt.cpp b/src/core/net/proxying_restricted_cookie_manager_qt.cpp index 0109f5697..d4d5cc4ab 100644 --- a/src/core/net/proxying_restricted_cookie_manager_qt.cpp +++ b/src/core/net/proxying_restricted_cookie_manager_qt.cpp @@ -10,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" @@ -29,7 +27,7 @@ void ProxyingRestrictedCookieManagerQt::CreateAndBind(ProfileIODataQt *profileIo { 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), @@ -67,14 +65,15 @@ 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::CookieWithAccessResult>()); } @@ -84,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); } @@ -98,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); diff --git a/src/core/net/proxying_restricted_cookie_manager_qt.h b/src/core/net/proxying_restricted_cookie_manager_qt.h index 7b897e5a4..faf0545c3 100644 --- a/src/core/net/proxying_restricted_cookie_manager_qt.h +++ b/src/core/net/proxying_restricted_cookie_manager_qt.h @@ -27,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: diff --git a/src/core/net/proxying_url_loader_factory_qt.cpp b/src/core/net/proxying_url_loader_factory_qt.cpp index 43fba5583..3a83ed7ea 100644 --- a/src/core/net/proxying_url_loader_factory_qt.cpp +++ b/src/core/net/proxying_url_loader_factory_qt.cpp @@ -5,7 +5,7 @@ #include <utility> -#include "base/bind.h" +#include "base/functional/bind.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" @@ -24,12 +24,25 @@ #include "web_contents_adapter.h" #include "web_contents_adapter_client.h" #include "web_contents_view_qt.h" +#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) @@ -68,6 +81,18 @@ 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 @@ -86,12 +111,10 @@ 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 {} @@ -104,8 +127,6 @@ public: void PauseReadingBodyFromNet() override; void ResumeReadingBodyFromNet() override; - static inline void cleanup(QWebEngineUrlRequestInfo *info) { delete info; } - private: void InterceptOnUIThread(); void ContinueAfterIntercept(); @@ -143,11 +164,18 @@ private: // 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_; - QScopedPointer<QWebEngineUrlRequestInfo, InterceptedRequest> request_info_; + 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_; @@ -170,6 +198,7 @@ InterceptedRequest::InterceptedRequest(ProfileAdapter *profile_adapter, , request_id_(request_id) , options_(options) , request_(request) + , request_body_(ResourceRequestBody(request_.request_body.get())) , traffic_annotation_(traffic_annotation) , proxied_loader_receiver_(this, std::move(loader_receiver)) , target_client_(std::move(client)) @@ -177,11 +206,7 @@ InterceptedRequest::InterceptedRequest(ProfileAdapter *profile_adapter, , weak_factory_(this) { const bool disable_web_security = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebSecurity); - current_response_ = network::mojom::URLResponseHead::New(); - current_response_->response_type = network::cors::CalculateResponseType( - request_.mode, - disable_web_security || ( - request_.request_initiator && request_.request_initiator->IsSameOriginWith(url::Origin::Create(request_.url)))); + current_response_ = createResponse(request_); // If there is a client error, clean up the request. target_client_.set_disconnect_handler( base::BindOnce(&InterceptedRequest::OnURLLoaderClientError, base::Unretained(this))); @@ -238,18 +263,25 @@ void InterceptedRequest::Restart() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + 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; + } + // Check if non-local access is allowed if (!allow_remote_ && remote_access_) { - bool granted_special_access = false; - switch (ui::PageTransition(request_.transition_type)) { - case ui::PAGE_TRANSITION_LINK: - case ui::PAGE_TRANSITION_TYPED: - if (blink::mojom::ResourceType(request_.resource_type) == blink::mojom::ResourceType::kMainFrame && request_.has_user_gesture) - granted_special_access = true; // allow normal explicit navigation - break; - default: - break; - } if (!granted_special_access) { target_client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_NETWORK_ACCESS_DENIED)); delete this; @@ -259,7 +291,6 @@ void InterceptedRequest::Restart() // Check if local access is allowed if (!allow_local_ && local_access_) { - bool granted_special_access = false; // 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(); @@ -286,7 +317,6 @@ void InterceptedRequest::Restart() } auto resourceType = toQt(blink::mojom::ResourceType(request_.resource_type)); - auto navigationType = toQt(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(); @@ -298,8 +328,14 @@ void InterceptedRequest::Restart() else firstPartyUrl = toQt(request_.site_for_cookies.first_party_url()); // m_topDocumentUrl can be empty for the main-frame. - auto info = new QWebEngineUrlRequestInfoPrivate(resourceType, navigationType, originalUrl, firstPartyUrl, - initiator, QByteArray::fromStdString(request_.method)); + 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)); @@ -325,22 +361,21 @@ void InterceptedRequest::ContinueAfterIntercept() if (request_info_) { // cleanup in scope because of delete this and it's not needed else where after - decltype(request_info_) scoped_request_info(request_info_.take()); + 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 (info.changed) { if (info.shouldBlockRequest) return SendErrorAndCompleteImmediately(net::ERR_BLOCKED_BY_CLIENT); - for (auto header = info.extraHeaders.constBegin(); header != info.extraHeaders.constEnd(); ++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.shouldRedirectRequest) { net::RedirectInfo::FirstPartyURLPolicy first_party_url_policy = request_.update_first_party_url_on_redirect ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT @@ -350,9 +385,6 @@ void InterceptedRequest::ContinueAfterIntercept() first_party_url_policy, request_.referrer_policy, request_.referrer.spec(), net::HTTP_TEMPORARY_REDIRECT, toGurl(info.url), absl::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; @@ -360,6 +392,11 @@ void InterceptedRequest::ContinueAfterIntercept() 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; } @@ -376,11 +413,11 @@ 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) @@ -400,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 diff --git a/src/core/net/qrc_url_scheme_handler.cpp b/src/core/net/qrc_url_scheme_handler.cpp index 416fb82ff..a8b4e4388 100644 --- a/src/core/net/qrc_url_scheme_handler.cpp +++ b/src/core/net/qrc_url_scheme_handler.cpp @@ -10,6 +10,8 @@ #include <QMimeDatabase> #include <QMimeType> +#include <memory> + namespace QtWebEngineCore { void QrcUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job) @@ -22,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); @@ -31,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/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 2c64132f3..41967f14e 100644 --- a/src/core/net/ssl_host_state_delegate_qt.cpp +++ b/src/core/net/ssl_host_state_delegate_qt.cpp @@ -3,7 +3,7 @@ #include "ssl_host_state_delegate_qt.h" -#include "base/callback.h" +#include "base/functional/callback.h" namespace QtWebEngineCore { @@ -39,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); } @@ -67,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; } @@ -83,12 +83,12 @@ bool SSLHostStateDelegateQt::DidHostRunInsecureContent(const std::string &host, return false; } -void SSLHostStateDelegateQt::AllowHttpForHost(const std::string &host, content::WebContents *web_contents) +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::WebContents *web_contents) +bool SSLHostStateDelegateQt::IsHttpAllowedForHost(const std::string &host, content::StoragePartition *web_contents) { return false; } @@ -104,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 ff25a0587..0b3d7974c 100644 --- a/src/core/net/ssl_host_state_delegate_qt.h +++ b/src/core/net/ssl_host_state_delegate_qt.h @@ -32,15 +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::WebContents *web_contents) override; - bool IsHttpAllowedForHost(const std::string &host, content::WebContents *web_contents) 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 a804ff8f7..439d1066c 100644 --- a/src/core/net/system_network_context_manager.cpp +++ b/src/core/net/system_network_context_manager.cpp @@ -8,8 +8,8 @@ #include "net/system_network_context_manager.h" -#include "base/bind.h" #include "base/command_line.h" +#include "base/functional/bind.h" #include "base/strings/string_split.h" #include "chrome/browser/net/chrome_mojo_proxy_resolver_factory.h" #include "chrome/common/chrome_switches.h" @@ -29,17 +29,26 @@ #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 "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; } @@ -48,6 +57,8 @@ 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::kAuthServerAllowlist); // auth_dynamic_params->delegate_allowlist = command_line->GetSwitchValueASCII(switches::kAuthNegotiateDelegateWhitelist); @@ -58,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 @@ -185,28 +201,45 @@ void SystemNetworkContextManager::OnNetworkServiceCreated(network::mojom::Networ network_service->SetUpHttpAuth(CreateHttpAuthStaticParams()); network_service->ConfigureHttpAuthPrefs(CreateHttpAuthDynamicParams()); +#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::TimeDelta>> disqualified_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; - std::string log_id = crypto::SHA256HashString(log_info->public_key); auto it = std::lower_bound( - std::begin(disqualified_logs), std::end(disqualified_logs), log_id, + 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_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()); + std::move(log_list_mojo), + certificate_transparency::GetLogListTimestamp(), + base::DoNothing()); // The system NetworkContext is created first network_service_network_context_.reset(); @@ -231,12 +264,13 @@ void SystemNetworkContextManager::OnNetworkServiceCreated(network::mojom::Networ network_service->SetExplicitlyAllowedPorts(explicitly_allowed_network_ports); } - // 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; - // absl::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)); + + // 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) @@ -254,8 +288,23 @@ void SystemNetworkContextManager::ConfigureDefaultNetworkContextParams(network:: // respect prefs::kEnableReferrers from the appropriate pref store. network_context_params->enable_referrers = false; - network_context_params->proxy_resolver_factory = ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver(); + 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 @@ -281,3 +330,30 @@ network::mojom::NetworkContextParamsPtr SystemNetworkContextManager::CreateNetwo 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 fa761cb44..d56bdab78 100644 --- a/src/core/net/system_network_context_manager.h +++ b/src/core/net/system_network_context_manager.h @@ -28,6 +28,8 @@ class URLLoaderFactory; class SharedURLLoaderFactory; } // namespace network +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 // not associated with a profile. It stores no data on disk, and has no HTTP @@ -114,4 +116,6 @@ private: ProxyConfigMonitor proxy_config_monitor_; }; +} // 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 d05b7d5a0..c877de669 100644 --- a/src/core/net/url_request_custom_job_delegate.cpp +++ b/src/core/net/url_request_custom_job_delegate.cpp @@ -4,7 +4,6 @@ #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" @@ -15,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)) { } @@ -52,13 +51,25 @@ 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) QObject::connect(device, &QIODevice::readyRead, this, &URLRequestCustomJobDelegate::slotReadyRead); m_proxy->m_ioTaskRunner->PostTask(FROM_HERE, - base::BindOnce(&URLRequestCustomJobProxy::reply, - m_proxy, contentType.toStdString(),device)); + 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 7b0d6538c..63db46464 100644 --- a/src/core/net/url_request_custom_job_delegate.h +++ b/src/core/net/url_request_custom_job_delegate.h @@ -17,6 +17,7 @@ #include "base/memory/ref_counted.h" #include "qtwebenginecoreglobal_p.h" +#include "resource_request_body_qt.h" #include <QMap> #include <QObject> @@ -24,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: @@ -47,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(); @@ -57,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; @@ -69,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 45372f020..0f41a3670 100644 --- a/src/core/net/url_request_custom_job_proxy.cpp +++ b/src/core/net/url_request_custom_job_proxy.cpp @@ -6,6 +6,7 @@ #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" @@ -40,7 +41,8 @@ void URLRequestCustomJobProxy::release() } } -void URLRequestCustomJobProxy::reply(std::string contentType, QIODevice *device) +void URLRequestCustomJobProxy::reply(std::string contentType, QIODevice *device, + QMultiMap<QByteArray, QByteArray> additionalResponseHeaders) { if (!m_client) return; @@ -50,14 +52,15 @@ void URLRequestCustomJobProxy::reply(std::string contentType, QIODevice *device) if (sidx > 0) { const int cidx = qcontentType.indexOf("charset=", sidx); if (cidx > 0) { - m_client->m_charset = qcontentType.mid(cidx + 8).toStdString(); + 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.toStdString(); + 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); @@ -124,7 +127,8 @@ void URLRequestCustomJobProxy::readyRead() void URLRequestCustomJobProxy::initialize(GURL url, std::string method, absl::optional<url::Origin> initiator, - std::map<std::string, std::string> headers) + std::map<std::string, std::string> headers, + scoped_refptr<network::ResourceRequestBody> requestBody) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); Q_ASSERT(!m_delegate); @@ -142,10 +146,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 3795f7f14..65c919ed0 100644 --- a/src/core/net/url_request_custom_job_proxy.h +++ b/src/core/net/url_request_custom_job_proxy.h @@ -4,15 +4,20 @@ #ifndef URL_REQUEST_CUSTOM_JOB_PROXY_H_ #define URL_REQUEST_CUSTOM_JOB_PROXY_H_ -#include "base/memory/weak_ptr.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; @@ -29,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; @@ -49,12 +55,15 @@ 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 release(); - void initialize(GURL url, std::string method, absl::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 acb0b3fcc..ed35a3e36 100644 --- a/src/core/net/webui_controller_factory_qt.cpp +++ b/src/core/net/webui_controller_factory_qt.cpp @@ -9,15 +9,14 @@ #include "webui_controller_factory_qt.h" #include "build_config_qt.h" - -#include "base/bind.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/net_internals/net_internals_ui.h" -#include "chrome/browser/ui/webui/quota_internals/quota_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_ui.h" @@ -26,8 +25,9 @@ #include "media/media_buildflags.h" #include "printing/buildflags/buildflags.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 @@ -86,22 +86,19 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, co // 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::kChromeUINetInternalsHost) + if (url.host_piece() == chrome::kChromeUINetInternalsHost) return &NewWebUI<NetInternalsUI>; - if (url.host() == chrome::kChromeUIQuotaInternalsHost) - return &NewWebUI<QuotaInternalsUI>; - 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) @@ -110,6 +107,9 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, co 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>; // @@ -131,7 +131,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI *web_ui, Profile *profile, co if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) return &NewWebUI<WebRtcLogsUI>; #endif -#if defined(OS_LINUX) || defined(OS_ANDROID) +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) if (url.host_piece() == chrome::kChromeUISandboxHost) return &NewWebUI<SandboxInternalsUI>; #endif |