WebKitWebContext.cpp [plain text]
#include "config.h"
#include "WebKitWebContext.h"
#include "APIAutomationClient.h"
#include "APIDownloadClient.h"
#include "APIInjectedBundleClient.h"
#include "APIPageConfiguration.h"
#include "APIProcessPoolConfiguration.h"
#include "APIString.h"
#include "LegacyGlobalSettings.h"
#include "NetworkProcessMessages.h"
#include "TextChecker.h"
#include "TextCheckerState.h"
#include "WebAutomationSession.h"
#include "WebCertificateInfo.h"
#include "WebKitAutomationSessionPrivate.h"
#include "WebKitDownloadClient.h"
#include "WebKitDownloadPrivate.h"
#include "WebKitFaviconDatabasePrivate.h"
#include "WebKitGeolocationManagerPrivate.h"
#include "WebKitInitialize.h"
#include "WebKitInjectedBundleClient.h"
#include "WebKitNotificationProvider.h"
#include "WebKitPrivate.h"
#include "WebKitProtocolHandler.h"
#include "WebKitSecurityManagerPrivate.h"
#include "WebKitSecurityOriginPrivate.h"
#include "WebKitSettingsPrivate.h"
#include "WebKitURISchemeRequestPrivate.h"
#include "WebKitUserContentManagerPrivate.h"
#include "WebKitUserMessagePrivate.h"
#include "WebKitWebContextPrivate.h"
#include "WebKitWebViewPrivate.h"
#include "WebKitWebsiteDataManagerPrivate.h"
#include "WebKitWebsitePoliciesPrivate.h"
#include "WebNotificationManagerProxy.h"
#include "WebProcessMessages.h"
#include "WebURLSchemeHandler.h"
#include "WebsiteDataStore.h"
#include "WebsiteDataType.h"
#include <JavaScriptCore/RemoteInspector.h>
#include <glib/gi18n-lib.h>
#include <libintl.h>
#include <memory>
#include <pal/HysteresisActivity.h>
#include <wtf/FileSystem.h>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/Language.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/RefCounted.h>
#include <wtf/RefPtr.h>
#include <wtf/URLParser.h>
#include <wtf/glib/GRefPtr.h>
#include <wtf/glib/GUniquePtr.h>
#include <wtf/glib/WTFGType.h>
#include <wtf/text/CString.h>
#if PLATFORM(GTK)
#include "WebKitRemoteInspectorProtocolHandler.h"
#endif
using namespace WebKit;
enum {
PROP_0,
#if PLATFORM(GTK)
PROP_LOCAL_STORAGE_DIRECTORY,
#endif
PROP_WEBSITE_DATA_MANAGER,
#if PLATFORM(GTK)
PROP_PSON_ENABLED,
#if !USE(GTK4)
PROP_USE_SYSYEM_APPEARANCE_FOR_SCROLLBARS
#endif
#endif
};
enum {
DOWNLOAD_STARTED,
INITIALIZE_WEB_EXTENSIONS,
INITIALIZE_NOTIFICATION_PERMISSIONS,
AUTOMATION_STARTED,
USER_MESSAGE_RECEIVED,
LAST_SIGNAL
};
class WebKitURISchemeHandler final : public WebURLSchemeHandler {
public:
static Ref<WebKitURISchemeHandler> create(WebKitWebContext* context, WebKitURISchemeRequestCallback callback, void* userData, GDestroyNotify destroyNotify)
{
return adoptRef(*new WebKitURISchemeHandler(context, callback, userData, destroyNotify));
}
~WebKitURISchemeHandler()
{
if (m_destroyNotify)
m_destroyNotify(m_userData);
}
private:
WebKitURISchemeHandler(WebKitWebContext* context, WebKitURISchemeRequestCallback callback, void* userData, GDestroyNotify destroyNotify)
: m_context(context)
, m_callback(callback)
, m_userData(userData)
, m_destroyNotify(destroyNotify)
{
}
void platformStartTask(WebPageProxy& page, WebURLSchemeTask& task) final
{
if (!m_callback)
return;
GRefPtr<WebKitURISchemeRequest> request = adoptGRef(webkitURISchemeRequestCreate(m_context, page, task));
auto addResult = m_requests.add(task.identifier(), WTFMove(request));
ASSERT(addResult.isNewEntry);
m_callback(addResult.iterator->value.get(), m_userData);
}
void platformStopTask(WebPageProxy&, WebURLSchemeTask& task) final
{
auto it = m_requests.find(task.identifier());
if (it == m_requests.end())
return;
webkitURISchemeRequestCancel(it->value.get());
m_requests.remove(it);
}
void platformTaskCompleted(WebURLSchemeTask& task) final
{
m_requests.remove(task.identifier());
}
WebKitWebContext* m_context { nullptr };
WebKitURISchemeRequestCallback m_callback { nullptr };
void* m_userData { nullptr };
GDestroyNotify m_destroyNotify { nullptr };
HashMap<uint64_t, GRefPtr<WebKitURISchemeRequest>> m_requests;
};
typedef HashMap<String, RefPtr<WebKitURISchemeHandler> > URISchemeHandlerMap;
typedef HashMap<uint64_t, GRefPtr<WebKitURISchemeRequest> > URISchemeRequestMap;
class WebKitAutomationClient;
struct _WebKitWebContextPrivate {
_WebKitWebContextPrivate()
: dnsPrefetchHystereris([this](PAL::HysteresisState state) { if (state == PAL::HysteresisState::Stopped) dnsPrefetchedHosts.clear(); })
{
}
RefPtr<WebProcessPool> processPool;
bool clientsDetached;
#if PLATFORM(GTK)
bool psonEnabled;
#if !USE(GTK4)
bool useSystemAppearanceForScrollbars;
#endif
#endif
GRefPtr<WebKitFaviconDatabase> faviconDatabase;
GRefPtr<WebKitSecurityManager> securityManager;
URISchemeHandlerMap uriSchemeHandlers;
GRefPtr<WebKitGeolocationManager> geolocationManager;
std::unique_ptr<WebKitNotificationProvider> notificationProvider;
GRefPtr<WebKitWebsiteDataManager> websiteDataManager;
CString faviconDatabaseDirectory;
WebKitProcessModel processModel;
HashMap<WebPageProxyIdentifier, WebKitWebView*> webViews;
CString webExtensionsDirectory;
GRefPtr<GVariant> webExtensionsInitializationUserData;
CString localStorageDirectory;
#if ENABLE(REMOTE_INSPECTOR)
#if PLATFORM(GTK)
std::unique_ptr<RemoteInspectorProtocolHandler> remoteInspectorProtocolHandler;
#endif
std::unique_ptr<WebKitAutomationClient> automationClient;
GRefPtr<WebKitAutomationSession> automationSession;
#endif
std::unique_ptr<WebKitProtocolHandler> webkitProtocolHandler;
HashSet<String> dnsPrefetchedHosts;
PAL::HysteresisActivity dnsPrefetchHystereris;
};
static guint signals[LAST_SIGNAL] = { 0, };
#if ENABLE(REMOTE_INSPECTOR)
class WebKitAutomationClient final : Inspector::RemoteInspector::Client {
WTF_MAKE_FAST_ALLOCATED;
public:
explicit WebKitAutomationClient(WebKitWebContext* context)
: m_webContext(context)
{
Inspector::RemoteInspector::singleton().setClient(this);
}
~WebKitAutomationClient()
{
Inspector::RemoteInspector::singleton().setClient(nullptr);
}
private:
bool remoteAutomationAllowed() const override { return true; }
String browserName() const override
{
if (!m_webContext->priv->automationSession)
return { };
return webkitAutomationSessionGetBrowserName(m_webContext->priv->automationSession.get());
}
String browserVersion() const override
{
if (!m_webContext->priv->automationSession)
return { };
return webkitAutomationSessionGetBrowserVersion(m_webContext->priv->automationSession.get());
}
void requestAutomationSession(const String& sessionIdentifier, const Inspector::RemoteInspector::Client::SessionCapabilities& capabilities) override
{
ASSERT(!m_webContext->priv->automationSession);
m_webContext->priv->automationSession = adoptGRef(webkitAutomationSessionCreate(m_webContext, sessionIdentifier.utf8().data(), capabilities));
g_signal_emit(m_webContext, signals[AUTOMATION_STARTED], 0, m_webContext->priv->automationSession.get());
m_webContext->priv->processPool->setAutomationSession(&webkitAutomationSessionGetSession(m_webContext->priv->automationSession.get()));
}
WebKitWebContext* m_webContext;
};
void webkitWebContextWillCloseAutomationSession(WebKitWebContext* webContext)
{
webContext->priv->processPool->setAutomationSession(nullptr);
webContext->priv->automationSession = nullptr;
}
#endif // ENABLE(REMOTE_INSPECTOR)
WEBKIT_DEFINE_TYPE(WebKitWebContext, webkit_web_context, G_TYPE_OBJECT)
#if PLATFORM(GTK)
#define INJECTED_BUNDLE_FILENAME "libwebkit2gtkinjectedbundle.so"
#elif PLATFORM(WPE)
#define INJECTED_BUNDLE_FILENAME "libWPEInjectedBundle.so"
#endif
static const char* injectedBundleDirectory()
{
#if ENABLE(DEVELOPER_MODE)
const char* bundleDirectory = g_getenv("WEBKIT_INJECTED_BUNDLE_PATH");
if (bundleDirectory && g_file_test(bundleDirectory, G_FILE_TEST_IS_DIR))
return bundleDirectory;
#endif
#if PLATFORM(GTK)
static const char* injectedBundlePath = LIBDIR G_DIR_SEPARATOR_S "webkit2gtk-" WEBKITGTK_API_VERSION_STRING
G_DIR_SEPARATOR_S "injected-bundle" G_DIR_SEPARATOR_S;
return injectedBundlePath;
#elif PLATFORM(WPE)
static const char* injectedBundlePath = PKGLIBDIR G_DIR_SEPARATOR_S "injected-bundle" G_DIR_SEPARATOR_S;
return injectedBundlePath;
#endif
}
static void webkitWebContextGetProperty(GObject* object, guint propID, GValue* value, GParamSpec* paramSpec)
{
WebKitWebContext* context = WEBKIT_WEB_CONTEXT(object);
switch (propID) {
#if PLATFORM(GTK)
case PROP_LOCAL_STORAGE_DIRECTORY:
g_value_set_string(value, context->priv->localStorageDirectory.data());
break;
#endif
case PROP_WEBSITE_DATA_MANAGER:
g_value_set_object(value, webkit_web_context_get_website_data_manager(context));
break;
#if PLATFORM(GTK)
case PROP_PSON_ENABLED:
g_value_set_boolean(value, context->priv->psonEnabled);
break;
#if !USE(GTK4)
case PROP_USE_SYSYEM_APPEARANCE_FOR_SCROLLBARS:
g_value_set_boolean(value, webkit_web_context_get_use_system_appearance_for_scrollbars(context));
break;
#endif
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, paramSpec);
}
}
static void webkitWebContextSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* paramSpec)
{
WebKitWebContext* context = WEBKIT_WEB_CONTEXT(object);
switch (propID) {
#if PLATFORM(GTK)
case PROP_LOCAL_STORAGE_DIRECTORY:
context->priv->localStorageDirectory = g_value_get_string(value);
break;
#endif
case PROP_WEBSITE_DATA_MANAGER: {
gpointer manager = g_value_get_object(value);
context->priv->websiteDataManager = manager ? WEBKIT_WEBSITE_DATA_MANAGER(manager) : nullptr;
break;
}
#if PLATFORM(GTK)
case PROP_PSON_ENABLED:
context->priv->psonEnabled = g_value_get_boolean(value);
break;
#if !USE(GTK4)
case PROP_USE_SYSYEM_APPEARANCE_FOR_SCROLLBARS:
webkit_web_context_set_use_system_appearance_for_scrollbars(context, g_value_get_boolean(value));
break;
#endif
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, paramSpec);
}
}
static void webkitWebContextConstructed(GObject* object)
{
G_OBJECT_CLASS(webkit_web_context_parent_class)->constructed(object);
GUniquePtr<char> bundleFilename(g_build_filename(injectedBundleDirectory(), INJECTED_BUNDLE_FILENAME, nullptr));
WebKitWebContext* webContext = WEBKIT_WEB_CONTEXT(object);
WebKitWebContextPrivate* priv = webContext->priv;
API::ProcessPoolConfiguration configuration;
configuration.setInjectedBundlePath(FileSystem::stringFromFileSystemRepresentation(bundleFilename.get()));
configuration.setUsesWebProcessCache(true);
#if PLATFORM(GTK)
configuration.setProcessSwapsOnNavigation(priv->psonEnabled);
#if !USE(GTK4)
configuration.setUseSystemAppearanceForScrollbars(priv->useSystemAppearanceForScrollbars);
#endif
#endif
if (!priv->websiteDataManager)
priv->websiteDataManager = adoptGRef(webkit_website_data_manager_new("local-storage-directory", priv->localStorageDirectory.data(), nullptr));
priv->processPool = WebProcessPool::create(configuration);
priv->processPool->setUserMessageHandler([webContext](UserMessage&& message, CompletionHandler<void(UserMessage&&)>&& completionHandler) {
GRefPtr<WebKitUserMessage> userMessage = webkitUserMessageCreate(WTFMove(message), WTFMove(completionHandler));
gboolean returnValue;
g_signal_emit(webContext, signals[USER_MESSAGE_RECEIVED], 0, userMessage.get(), &returnValue);
});
priv->processModel = WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES;
#if ENABLE(MEMORY_SAMPLER)
if (getenv("WEBKIT_SAMPLE_MEMORY"))
priv->processPool->startMemorySampler(0);
#endif
attachInjectedBundleClientToContext(webContext);
attachDownloadClientToContext(webContext);
priv->geolocationManager = adoptGRef(webkitGeolocationManagerCreate(priv->processPool->supplement<WebGeolocationManagerProxy>()));
priv->notificationProvider = makeUnique<WebKitNotificationProvider>(priv->processPool->supplement<WebNotificationManagerProxy>(), webContext);
#if PLATFORM(GTK) && ENABLE(REMOTE_INSPECTOR)
priv->remoteInspectorProtocolHandler = makeUnique<RemoteInspectorProtocolHandler>(webContext);
#endif
priv->webkitProtocolHandler = makeUnique<WebKitProtocolHandler>(webContext);
}
static void webkitWebContextDispose(GObject* object)
{
WebKitWebContextPrivate* priv = WEBKIT_WEB_CONTEXT(object)->priv;
if (!priv->clientsDetached) {
priv->clientsDetached = true;
priv->processPool->setInjectedBundleClient(nullptr);
priv->processPool->setLegacyDownloadClient(nullptr);
}
if (priv->faviconDatabase) {
webkitFaviconDatabaseClose(priv->faviconDatabase.get());
priv->faviconDatabase = nullptr;
}
if (priv->processPool) {
priv->processPool->setUserMessageHandler(nullptr);
priv->processPool = nullptr;
}
G_OBJECT_CLASS(webkit_web_context_parent_class)->dispose(object);
}
static void webkit_web_context_class_init(WebKitWebContextClass* webContextClass)
{
webkitInitialize();
GObjectClass* gObjectClass = G_OBJECT_CLASS(webContextClass);
bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
gObjectClass->get_property = webkitWebContextGetProperty;
gObjectClass->set_property = webkitWebContextSetProperty;
gObjectClass->constructed = webkitWebContextConstructed;
gObjectClass->dispose = webkitWebContextDispose;
#if PLATFORM(GTK)
g_object_class_install_property(
gObjectClass,
PROP_LOCAL_STORAGE_DIRECTORY,
g_param_spec_string(
"local-storage-directory",
_("Local Storage Directory"),
_("The directory where local storage data will be saved"),
nullptr,
static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)));
#endif
g_object_class_install_property(
gObjectClass,
PROP_WEBSITE_DATA_MANAGER,
g_param_spec_object(
"website-data-manager",
_("Website Data Manager"),
_("The WebKitWebsiteDataManager associated with this context"),
WEBKIT_TYPE_WEBSITE_DATA_MANAGER,
static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)));
#if PLATFORM(GTK)
g_object_class_install_property(
gObjectClass,
PROP_PSON_ENABLED,
g_param_spec_boolean(
"process-swap-on-cross-site-navigation-enabled",
_("Swap Processes on Cross-Site Navigation"),
_("Whether swap Web processes on cross-site navigations is enabled"),
FALSE,
static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)));
#if !USE(GTK4)
g_object_class_install_property(
gObjectClass,
PROP_USE_SYSYEM_APPEARANCE_FOR_SCROLLBARS,
g_param_spec_boolean(
"use-system-appearance-for-scrollbars",
_("Use system appearance for scrollbars"),
_("Whether to use system appearance for rendering scrollbars"),
TRUE,
static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT)));
#endif
#endif
signals[DOWNLOAD_STARTED] =
g_signal_new("download-started",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET(WebKitWebContextClass, download_started),
nullptr, nullptr,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE, 1,
WEBKIT_TYPE_DOWNLOAD);
signals[INITIALIZE_WEB_EXTENSIONS] =
g_signal_new("initialize-web-extensions",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET(WebKitWebContextClass, initialize_web_extensions),
nullptr, nullptr,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals[INITIALIZE_NOTIFICATION_PERMISSIONS] =
g_signal_new("initialize-notification-permissions",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET(WebKitWebContextClass, initialize_notification_permissions),
nullptr, nullptr,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals[AUTOMATION_STARTED] =
g_signal_new("automation-started",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET(WebKitWebContextClass, automation_started),
nullptr, nullptr,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE, 1,
WEBKIT_TYPE_AUTOMATION_SESSION);
signals[USER_MESSAGE_RECEIVED] = g_signal_new(
"user-message-received",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET(WebKitWebContextClass, user_message_received),
g_signal_accumulator_true_handled, nullptr,
g_cclosure_marshal_generic,
G_TYPE_BOOLEAN, 1,
WEBKIT_TYPE_USER_MESSAGE);
}
static gpointer createDefaultWebContext(gpointer)
{
static GRefPtr<WebKitWebContext> webContext = adoptGRef(WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, nullptr)));
return webContext.get();
}
WebKitWebContext* webkit_web_context_get_default(void)
{
static GOnce onceInit = G_ONCE_INIT;
return WEBKIT_WEB_CONTEXT(g_once(&onceInit, createDefaultWebContext, 0));
}
WebKitWebContext* webkit_web_context_new(void)
{
return WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, nullptr));
}
WebKitWebContext* webkit_web_context_new_ephemeral()
{
GRefPtr<WebKitWebsiteDataManager> manager = adoptGRef(webkit_website_data_manager_new_ephemeral());
return WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, "website-data-manager", manager.get(), nullptr));
}
WebKitWebContext* webkit_web_context_new_with_website_data_manager(WebKitWebsiteDataManager* manager)
{
g_return_val_if_fail(WEBKIT_IS_WEBSITE_DATA_MANAGER(manager), nullptr);
return WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, "website-data-manager", manager, nullptr));
}
WebKitWebsiteDataManager* webkit_web_context_get_website_data_manager(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), nullptr);
return context->priv->websiteDataManager.get();
}
gboolean webkit_web_context_is_ephemeral(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), FALSE);
return webkit_website_data_manager_is_ephemeral(context->priv->websiteDataManager.get());
}
gboolean webkit_web_context_is_automation_allowed(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), FALSE);
#if ENABLE(REMOTE_INSPECTOR)
return !!context->priv->automationClient;
#else
return FALSE;
#endif
}
void webkit_web_context_set_automation_allowed(WebKitWebContext* context, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
if (webkit_web_context_is_automation_allowed(context) == allowed)
return;
#if ENABLE(REMOTE_INSPECTOR)
if (allowed) {
if (Inspector::RemoteInspector::singleton().client()) {
g_warning("Not enabling automation on WebKitWebContext because there's another context with automation enabled, only one is allowed");
return;
}
context->priv->automationClient = makeUnique<WebKitAutomationClient>(context);
} else
context->priv->automationClient = nullptr;
#endif
}
void webkit_web_context_set_cache_model(WebKitWebContext*, WebKitCacheModel model)
{
CacheModel cacheModel;
switch (model) {
case WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER:
cacheModel = CacheModel::DocumentViewer;
break;
case WEBKIT_CACHE_MODEL_WEB_BROWSER:
cacheModel = CacheModel::PrimaryWebBrowser;
break;
case WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER:
cacheModel = CacheModel::DocumentBrowser;
break;
default:
g_assert_not_reached();
}
if (cacheModel != LegacyGlobalSettings::singleton().cacheModel())
LegacyGlobalSettings::singleton().setCacheModel(cacheModel);
}
WebKitCacheModel webkit_web_context_get_cache_model(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), WEBKIT_CACHE_MODEL_WEB_BROWSER);
switch (LegacyGlobalSettings::singleton().cacheModel()) {
case CacheModel::DocumentViewer:
return WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER;
case CacheModel::PrimaryWebBrowser:
return WEBKIT_CACHE_MODEL_WEB_BROWSER;
case CacheModel::DocumentBrowser:
return WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER;
default:
g_assert_not_reached();
}
return WEBKIT_CACHE_MODEL_WEB_BROWSER;
}
void webkit_web_context_clear_cache(WebKitWebContext* context)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
OptionSet<WebsiteDataType> websiteDataTypes;
websiteDataTypes.add(WebsiteDataType::MemoryCache);
websiteDataTypes.add(WebsiteDataType::DiskCache);
auto& websiteDataStore = webkitWebsiteDataManagerGetDataStore(context->priv->websiteDataManager.get());
websiteDataStore.removeData(websiteDataTypes, -WallTime::infinity(), [] { });
}
void webkit_web_context_set_network_proxy_settings(WebKitWebContext* context, WebKitNetworkProxyMode proxyMode, WebKitNetworkProxySettings* proxySettings)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
webkit_website_data_manager_set_network_proxy_settings(context->priv->websiteDataManager.get(), proxyMode, proxySettings);
}
typedef HashMap<DownloadProxy*, GRefPtr<WebKitDownload> > DownloadsMap;
static DownloadsMap& downloadsMap()
{
static NeverDestroyed<DownloadsMap> downloads;
return downloads;
}
WebKitDownload* webkit_web_context_download_uri(WebKitWebContext* context, const gchar* uri)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), nullptr);
g_return_val_if_fail(uri, nullptr);
GRefPtr<WebKitDownload> download = webkitWebContextStartDownload(context, uri, nullptr);
return download.leakRef();
}
WebKitCookieManager* webkit_web_context_get_cookie_manager(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), nullptr);
return webkit_website_data_manager_get_cookie_manager(context->priv->websiteDataManager.get());
}
WebKitGeolocationManager* webkit_web_context_get_geolocation_manager(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), nullptr);
return context->priv->geolocationManager.get();
}
static void ensureFaviconDatabase(WebKitWebContext* context)
{
WebKitWebContextPrivate* priv = context->priv;
if (priv->faviconDatabase)
return;
priv->faviconDatabase = adoptGRef(webkitFaviconDatabaseCreate());
}
void webkit_web_context_set_favicon_database_directory(WebKitWebContext* context, const gchar* path)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
WebKitWebContextPrivate* priv = context->priv;
ensureFaviconDatabase(context);
String directoryPath = FileSystem::stringFromFileSystemRepresentation(path);
if (directoryPath.isEmpty()) {
#if PLATFORM(GTK)
const char* portDirectory = "webkitgtk";
#elif PLATFORM(WPE)
const char* portDirectory = "wpe";
#endif
GUniquePtr<gchar> databaseDirectory(g_build_filename(g_get_user_cache_dir(), portDirectory, "icondatabase", nullptr));
directoryPath = FileSystem::stringFromFileSystemRepresentation(databaseDirectory.get());
}
priv->faviconDatabaseDirectory = directoryPath.utf8();
GUniquePtr<gchar> faviconDatabasePath(g_build_filename(priv->faviconDatabaseDirectory.data(),
"WebpageIcons.db", nullptr));
webkitFaviconDatabaseOpen(priv->faviconDatabase.get(), FileSystem::stringFromFileSystemRepresentation(faviconDatabasePath.get()), webkit_web_context_is_ephemeral(context));
}
const gchar* webkit_web_context_get_favicon_database_directory(WebKitWebContext *context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0);
WebKitWebContextPrivate* priv = context->priv;
if (priv->faviconDatabaseDirectory.isNull())
return 0;
return priv->faviconDatabaseDirectory.data();
}
WebKitFaviconDatabase* webkit_web_context_get_favicon_database(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0);
ensureFaviconDatabase(context);
return context->priv->faviconDatabase.get();
}
WebKitSecurityManager* webkit_web_context_get_security_manager(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0);
WebKitWebContextPrivate* priv = context->priv;
if (!priv->securityManager)
priv->securityManager = adoptGRef(webkitSecurityManagerCreate(context));
return priv->securityManager.get();
}
void webkit_web_context_set_additional_plugins_directory(WebKitWebContext*, const char*)
{
g_warning("webkit_web_context_set_additional_plugins_directory is deprecated and does nothing. Netscape plugins are no longer supported.");
}
void webkit_web_context_get_plugins(WebKitWebContext* context, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_warning("webkit_web_context_get_plugins is deprecated and always returns an empty list. Netscape plugins are no longer supported.");
GRefPtr<GTask> task = adoptGRef(g_task_new(context, cancellable, callback, userData));
g_task_return_pointer(task.get(), nullptr, nullptr);
}
GList* webkit_web_context_get_plugins_finish(WebKitWebContext* context, GAsyncResult* result, GError** error)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), nullptr);
g_return_val_if_fail(g_task_is_valid(result, context), nullptr);
return static_cast<GList*>(g_task_propagate_pointer(G_TASK(result), error));
}
void webkit_web_context_register_uri_scheme(WebKitWebContext* context, const char* scheme, WebKitURISchemeRequestCallback callback, gpointer userData, GDestroyNotify destroyNotify)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(scheme);
g_return_if_fail(callback);
auto canonicalizedScheme = WTF::URLParser::maybeCanonicalizeScheme(scheme);
if (!canonicalizedScheme) {
g_critical("Cannot register invalid URI scheme %s", scheme);
return;
}
if (WTF::URLParser::isSpecialScheme(canonicalizedScheme.value())) {
g_warning("Registering special URI scheme %s is no longer allowed", scheme);
return;
}
auto handler = WebKitURISchemeHandler::create(context, callback, userData, destroyNotify);
auto addResult = context->priv->uriSchemeHandlers.set(String::fromUTF8(scheme), WTFMove(handler));
for (auto* webView : context->priv->webViews.values())
webkitWebViewGetPage(webView).setURLSchemeHandlerForScheme(*addResult.iterator->value, String::fromUTF8(scheme));
}
void webkit_web_context_set_sandbox_enabled(WebKitWebContext* context, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
if (context->priv->processPool->processes().size())
g_error("Sandboxing cannot be changed after subprocesses were spawned.");
context->priv->processPool->setSandboxEnabled(enabled);
}
static bool pathIsBlocked(const char* path)
{
static const Vector<CString, 4> blockedPrefixes = {
"sys", "proc", "dev",
"", };
if (!g_path_is_absolute(path))
return true;
GUniquePtr<char*> splitPath(g_strsplit(path, G_DIR_SEPARATOR_S, 3));
return blockedPrefixes.contains(splitPath.get()[1]);
}
void webkit_web_context_add_path_to_sandbox(WebKitWebContext* context, const char* path, gboolean readOnly)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
if (pathIsBlocked(path)) {
g_critical("Attempted to add disallowed path to sandbox: %s", path);
return;
}
if (context->priv->processPool->processes().size())
g_error("Sandbox paths cannot be changed after subprocesses were spawned.");
auto permission = readOnly ? SandboxPermission::ReadOnly : SandboxPermission::ReadWrite;
context->priv->processPool->addSandboxPath(path, permission);
}
gboolean webkit_web_context_get_sandbox_enabled(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), FALSE);
return context->priv->processPool->sandboxEnabled();
}
gboolean webkit_web_context_get_spell_checking_enabled(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), FALSE);
#if ENABLE(SPELLCHECK)
return TextChecker::state().isContinuousSpellCheckingEnabled;
#else
return false;
#endif
}
void webkit_web_context_set_spell_checking_enabled(WebKitWebContext* context, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
#if ENABLE(SPELLCHECK)
TextChecker::setContinuousSpellCheckingEnabled(enabled);
#endif
}
const gchar* const* webkit_web_context_get_spell_checking_languages(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), nullptr);
#if ENABLE(SPELLCHECK)
Vector<String> spellCheckingLanguages = TextChecker::loadedSpellCheckingLanguages();
if (spellCheckingLanguages.isEmpty())
return nullptr;
static GRefPtr<GPtrArray> languagesToReturn;
languagesToReturn = adoptGRef(g_ptr_array_new_with_free_func(g_free));
for (const auto& language : spellCheckingLanguages)
g_ptr_array_add(languagesToReturn.get(), g_strdup(language.utf8().data()));
g_ptr_array_add(languagesToReturn.get(), nullptr);
return reinterpret_cast<char**>(languagesToReturn->pdata);
#else
return 0;
#endif
}
void webkit_web_context_set_spell_checking_languages(WebKitWebContext* context, const gchar* const* languages)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(languages);
#if ENABLE(SPELLCHECK)
Vector<String> spellCheckingLanguages;
for (size_t i = 0; languages[i]; ++i)
spellCheckingLanguages.append(String::fromUTF8(languages[i]));
TextChecker::setSpellCheckingLanguages(spellCheckingLanguages);
#endif
}
void webkit_web_context_set_preferred_languages(WebKitWebContext* context, const gchar* const* languageList)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
if (!languageList || !g_strv_length(const_cast<char**>(languageList)))
return;
Vector<String> languages;
for (size_t i = 0; languageList[i]; ++i) {
if (!g_ascii_strcasecmp(languageList[i], "C") || !g_ascii_strcasecmp(languageList[i], "POSIX"))
languages.append("en-US"_s);
else
languages.append(String::fromUTF8(languageList[i]).replace("_", "-"));
}
overrideUserPreferredLanguages(languages);
}
void webkit_web_context_set_tls_errors_policy(WebKitWebContext* context, WebKitTLSErrorsPolicy policy)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
webkit_website_data_manager_set_tls_errors_policy(context->priv->websiteDataManager.get(), policy);
}
WebKitTLSErrorsPolicy webkit_web_context_get_tls_errors_policy(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), WEBKIT_TLS_ERRORS_POLICY_IGNORE);
return webkit_website_data_manager_get_tls_errors_policy(context->priv->websiteDataManager.get());
}
void webkit_web_context_set_web_extensions_directory(WebKitWebContext* context, const char* directory)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(directory);
context->priv->webExtensionsDirectory = directory;
context->priv->processPool->addSandboxPath(directory, SandboxPermission::ReadOnly);
}
void webkit_web_context_set_web_extensions_initialization_user_data(WebKitWebContext* context, GVariant* userData)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(userData);
context->priv->webExtensionsInitializationUserData = userData;
}
#if PLATFORM(GTK)
void webkit_web_context_set_disk_cache_directory(WebKitWebContext*, const char*)
{
g_warning("webkit_web_context_set_disk_cache_directory is deprecated and does nothing, use WebKitWebsiteDataManager instead");
}
#endif
void webkit_web_context_prefetch_dns(WebKitWebContext* context, const char* hostname)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(hostname);
auto& websiteDataStore = webkitWebsiteDataManagerGetDataStore(context->priv->websiteDataManager.get());
websiteDataStore.networkProcess().send(Messages::NetworkProcess::PrefetchDNS(String::fromUTF8(hostname)), 0);
context->priv->dnsPrefetchHystereris.impulse();
}
void webkit_web_context_allow_tls_certificate_for_host(WebKitWebContext* context, GTlsCertificate* certificate, const gchar* host)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(G_IS_TLS_CERTIFICATE(certificate));
g_return_if_fail(host);
auto webCertificateInfo = WebCertificateInfo::create(WebCore::CertificateInfo(certificate, static_cast<GTlsCertificateFlags>(0)));
auto& websiteDataStore = webkitWebsiteDataManagerGetDataStore(context->priv->websiteDataManager.get());
websiteDataStore.allowSpecificHTTPSCertificateForHost(webCertificateInfo.ptr(), String::fromUTF8(host));
}
void webkit_web_context_set_process_model(WebKitWebContext* context, WebKitProcessModel processModel)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
if (processModel == WEBKIT_PROCESS_MODEL_SHARED_SECONDARY_PROCESS) {
g_warning("WEBKIT_PROCESS_MODEL_SHARED_SECONDARY_PROCESS is deprecated and has no effect");
return;
}
if (processModel == context->priv->processModel)
return;
context->priv->processModel = processModel;
}
WebKitProcessModel webkit_web_context_get_process_model(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
return context->priv->processModel;
}
void webkit_web_context_set_web_process_count_limit(WebKitWebContext* context, guint limit)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_warning("webkit_web_context_set_web_process_count_limit is deprecated and does nothing. Limiting the number of web processes is no longer possible for security reasons");
}
guint webkit_web_context_get_web_process_count_limit(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0);
return 0;
}
static void addOriginToMap(WebKitSecurityOrigin* origin, HashMap<String, bool>* map, bool allowed)
{
String string = webkitSecurityOriginGetSecurityOrigin(origin).toString();
if (string != "null")
map->set(string, allowed);
}
void webkit_web_context_initialize_notification_permissions(WebKitWebContext* context, GList* allowedOrigins, GList* disallowedOrigins)
{
HashMap<String, bool> map;
g_list_foreach(allowedOrigins, [](gpointer data, gpointer userData) {
addOriginToMap(static_cast<WebKitSecurityOrigin*>(data), static_cast<HashMap<String, bool>*>(userData), true);
}, &map);
g_list_foreach(disallowedOrigins, [](gpointer data, gpointer userData) {
addOriginToMap(static_cast<WebKitSecurityOrigin*>(data), static_cast<HashMap<String, bool>*>(userData), false);
}, &map);
context->priv->notificationProvider->setNotificationPermissions(WTFMove(map));
}
void webkit_web_context_send_message_to_all_extensions(WebKitWebContext* context, WebKitUserMessage* message)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
g_return_if_fail(WEBKIT_IS_USER_MESSAGE(message));
GRefPtr<WebKitUserMessage> adoptedMessage = message;
for (auto& process : context->priv->processPool->processes())
process->send(Messages::WebProcess::SendMessageToWebExtension(webkitUserMessageGetMessage(message)), 0);
}
#if PLATFORM(GTK) && !USE(GTK4)
void webkit_web_context_set_use_system_appearance_for_scrollbars(WebKitWebContext* context, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
if (context->priv->useSystemAppearanceForScrollbars == enabled)
return;
context->priv->useSystemAppearanceForScrollbars = enabled;
g_object_notify(G_OBJECT(context), "use-system-appearance-for-scrollbars");
if (!context->priv->processPool)
return;
context->priv->processPool->configuration().setUseSystemAppearanceForScrollbars(enabled);
context->priv->processPool->sendToAllProcesses(Messages::WebProcess::SetUseSystemAppearanceForScrollbars(enabled));
}
gboolean webkit_web_context_get_use_system_appearance_for_scrollbars(WebKitWebContext* context)
{
g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), TRUE);
return context->priv->useSystemAppearanceForScrollbars;
}
#endif
void webkitWebContextInitializeNotificationPermissions(WebKitWebContext* context)
{
g_signal_emit(context, signals[INITIALIZE_NOTIFICATION_PERMISSIONS], 0);
}
WebKitDownload* webkitWebContextGetOrCreateDownload(DownloadProxy* downloadProxy)
{
GRefPtr<WebKitDownload> download = downloadsMap().get(downloadProxy);
if (download)
return download.get();
download = adoptGRef(webkitDownloadCreate(downloadProxy));
downloadsMap().set(downloadProxy, download.get());
return download.get();
}
WebKitDownload* webkitWebContextStartDownload(WebKitWebContext* context, const char* uri, WebPageProxy* initiatingPage)
{
WebCore::ResourceRequest request(String::fromUTF8(uri));
auto& websiteDataStore = webkitWebsiteDataManagerGetDataStore(context->priv->websiteDataManager.get());
return webkitWebContextGetOrCreateDownload(&context->priv->processPool->download(websiteDataStore, initiatingPage, request));
}
void webkitWebContextRemoveDownload(DownloadProxy* downloadProxy)
{
downloadsMap().remove(downloadProxy);
}
void webkitWebContextDownloadStarted(WebKitWebContext* context, WebKitDownload* download)
{
g_signal_emit(context, signals[DOWNLOAD_STARTED], 0, download);
}
GVariant* webkitWebContextInitializeWebExtensions(WebKitWebContext* context)
{
g_signal_emit(context, signals[INITIALIZE_WEB_EXTENSIONS], 0);
return g_variant_new("(msmv)",
context->priv->webExtensionsDirectory.data(),
context->priv->webExtensionsInitializationUserData.get());
}
WebProcessPool& webkitWebContextGetProcessPool(WebKitWebContext* context)
{
g_assert(WEBKIT_IS_WEB_CONTEXT(context));
return *context->priv->processPool;
}
void webkitWebContextCreatePageForWebView(WebKitWebContext* context, WebKitWebView* webView, WebKitUserContentManager* userContentManager, WebKitWebView* relatedView, WebKitWebsitePolicies* defaultWebsitePolicies)
{
auto pageConfiguration = API::PageConfiguration::create();
pageConfiguration->setProcessPool(context->priv->processPool.get());
pageConfiguration->setPreferences(webkitSettingsGetPreferences(webkit_web_view_get_settings(webView)));
pageConfiguration->setRelatedPage(relatedView ? &webkitWebViewGetPage(relatedView) : nullptr);
pageConfiguration->setUserContentController(userContentManager ? webkitUserContentManagerGetUserContentControllerProxy(userContentManager) : nullptr);
pageConfiguration->setControlledByAutomation(webkit_web_view_is_controlled_by_automation(webView));
WebKitWebsiteDataManager* manager = webkitWebViewGetWebsiteDataManager(webView);
if (!manager)
manager = context->priv->websiteDataManager.get();
pageConfiguration->setWebsiteDataStore(&webkitWebsiteDataManagerGetDataStore(manager));
pageConfiguration->setDefaultWebsitePolicies(webkitWebsitePoliciesGetWebsitePolicies(defaultWebsitePolicies));
webkitWebViewCreatePage(webView, WTFMove(pageConfiguration));
auto& page = webkitWebViewGetPage(webView);
for (auto& it : context->priv->uriSchemeHandlers) {
Ref<WebURLSchemeHandler> handler(*it.value);
page.setURLSchemeHandlerForScheme(WTFMove(handler), it.key);
}
context->priv->webViews.set(page.identifier(), webView);
}
void webkitWebContextWebViewDestroyed(WebKitWebContext* context, WebKitWebView* webView)
{
context->priv->webViews.remove(webkitWebViewGetPage(webView).identifier());
}
WebKitWebView* webkitWebContextGetWebViewForPage(WebKitWebContext* context, WebPageProxy* page)
{
return page ? context->priv->webViews.get(page->identifier()) : nullptr;
}