2 * Copyright (C) 2016-2018 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "WebResourceLoadStatisticsStore.h"
30 #include "PluginProcessManager.h"
31 #include "PluginProcessProxy.h"
32 #include "WebProcessMessages.h"
33 #include "WebProcessProxy.h"
34 #include "WebResourceLoadStatisticsStoreMessages.h"
35 #include "WebResourceLoadStatisticsTelemetry.h"
36 #include "WebsiteDataFetchOption.h"
37 #include "WebsiteDataStore.h"
38 #include <WebCore/KeyedCoding.h>
39 #include <WebCore/ResourceLoadStatistics.h>
40 #include <wtf/CrossThreadCopier.h>
41 #include <wtf/DateMath.h>
42 #include <wtf/MathExtras.h>
43 #include <wtf/NeverDestroyed.h>
45 using namespace WebCore;
49 constexpr unsigned operatingDatesWindow { 30 };
50 constexpr unsigned statisticsModelVersion { 10 };
51 constexpr unsigned maxImportance { 3 };
53 template<typename T> static inline String isolatedPrimaryDomain(const T& value)
55 return ResourceLoadStatistics::primaryDomain(value).isolatedCopy();
58 const OptionSet<WebsiteDataType>& WebResourceLoadStatisticsStore::monitoredDataTypes()
60 static NeverDestroyed<OptionSet<WebsiteDataType>> dataTypes(std::initializer_list<WebsiteDataType>({
61 WebsiteDataType::Cookies,
62 WebsiteDataType::DOMCache,
63 WebsiteDataType::IndexedDBDatabases,
64 WebsiteDataType::LocalStorage,
65 WebsiteDataType::MediaKeys,
66 WebsiteDataType::OfflineWebApplicationCache,
67 #if ENABLE(NETSCAPE_PLUGIN_API)
68 WebsiteDataType::PlugInData,
70 WebsiteDataType::SearchFieldRecentSearches,
71 WebsiteDataType::SessionStorage,
72 #if ENABLE(SERVICE_WORKER)
73 WebsiteDataType::ServiceWorkerRegistrations,
75 WebsiteDataType::WebSQLDatabases,
78 ASSERT(RunLoop::isMain());
85 OperatingDate() = default;
87 static OperatingDate fromWallTime(WallTime time)
89 double ms = time.secondsSinceEpoch().milliseconds();
90 int year = msToYear(ms);
91 int yearDay = dayInYear(ms, year);
92 int month = monthFromDayInYear(yearDay, isLeapYear(year));
93 int monthDay = dayInMonthFromDayInYear(yearDay, isLeapYear(year));
95 return OperatingDate { year, month, monthDay };
98 static OperatingDate today()
100 return OperatingDate::fromWallTime(WallTime::now());
103 Seconds secondsSinceEpoch() const
105 return Seconds { dateToDaysFrom1970(m_year, m_month, m_monthDay) * secondsPerDay };
108 bool operator==(const OperatingDate& other) const
110 return m_monthDay == other.m_monthDay && m_month == other.m_month && m_year == other.m_year;
113 bool operator<(const OperatingDate& other) const
115 return secondsSinceEpoch() < other.secondsSinceEpoch();
118 bool operator<=(const OperatingDate& other) const
120 return secondsSinceEpoch() <= other.secondsSinceEpoch();
124 OperatingDate(int year, int month, int monthDay)
127 , m_monthDay(monthDay)
131 int m_month { 0 }; // [0, 11].
132 int m_monthDay { 0 }; // [1, 31].
135 static Vector<OperatingDate> mergeOperatingDates(const Vector<OperatingDate>& existingDates, Vector<OperatingDate>&& newDates)
137 if (existingDates.isEmpty())
138 return WTFMove(newDates);
140 Vector<OperatingDate> mergedDates(existingDates.size() + newDates.size());
142 // Merge the two sorted vectors of dates.
143 std::merge(existingDates.begin(), existingDates.end(), newDates.begin(), newDates.end(), mergedDates.begin());
144 // Remove duplicate dates.
145 removeRepeatedElements(mergedDates);
147 // Drop old dates until the Vector size reaches operatingDatesWindow.
148 while (mergedDates.size() > operatingDatesWindow)
149 mergedDates.remove(0);
154 WebResourceLoadStatisticsStore::WebResourceLoadStatisticsStore(const String& resourceLoadStatisticsDirectory, Function<void(const String&)>&& testingCallback, bool isEphemeral, UpdatePrevalentDomainsToPartitionOrBlockCookiesHandler&& updatePrevalentDomainsToPartitionOrBlockCookiesHandler, HasStorageAccessForFrameHandler&& hasStorageAccessForFrameHandler, GrantStorageAccessForFrameHandler&& grantStorageAccessForFrameHandler, RemovePrevalentDomainsHandler&& removeDomainsHandler)
155 : m_statisticsQueue(WorkQueue::create("WebResourceLoadStatisticsStore Process Data Queue", WorkQueue::Type::Serial, WorkQueue::QOS::Utility))
156 , m_persistentStorage(*this, resourceLoadStatisticsDirectory, isEphemeral ? ResourceLoadStatisticsPersistentStorage::IsReadOnly::Yes : ResourceLoadStatisticsPersistentStorage::IsReadOnly::No)
157 , m_updatePrevalentDomainsToPartitionOrBlockCookiesHandler(WTFMove(updatePrevalentDomainsToPartitionOrBlockCookiesHandler))
158 , m_hasStorageAccessForFrameHandler(WTFMove(hasStorageAccessForFrameHandler))
159 , m_grantStorageAccessForFrameHandler(WTFMove(grantStorageAccessForFrameHandler))
160 , m_removeDomainsHandler(WTFMove(removeDomainsHandler))
161 , m_dailyTasksTimer(RunLoop::main(), this, &WebResourceLoadStatisticsStore::performDailyTasks)
162 , m_statisticsTestingCallback(WTFMove(testingCallback))
164 ASSERT(RunLoop::isMain());
167 registerUserDefaultsIfNeeded();
170 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
171 m_persistentStorage.initialize();
172 includeTodayAsOperatingDateIfNecessary();
175 m_statisticsQueue->dispatchAfter(5_s, [this, protectedThis = makeRef(*this)] {
176 if (m_parameters.shouldSubmitTelemetry)
177 WebResourceLoadStatisticsTelemetry::calculateAndSubmit(*this);
180 m_dailyTasksTimer.startRepeating(24_h);
183 WebResourceLoadStatisticsStore::~WebResourceLoadStatisticsStore()
185 m_persistentStorage.finishAllPendingWorkSynchronously();
188 void WebResourceLoadStatisticsStore::removeDataRecords()
190 ASSERT(!RunLoop::isMain());
192 if (!shouldRemoveDataRecords())
195 #if ENABLE(NETSCAPE_PLUGIN_API)
196 m_activePluginTokens.clear();
197 for (auto plugin : PluginProcessManager::singleton().pluginProcesses())
198 m_activePluginTokens.add(plugin->pluginProcessToken());
201 auto prevalentResourceDomains = topPrivatelyControlledDomainsToRemoveWebsiteDataFor();
202 if (prevalentResourceDomains.isEmpty())
205 setDataRecordsBeingRemoved(true);
207 RunLoop::main().dispatch([prevalentResourceDomains = crossThreadCopy(prevalentResourceDomains), this, protectedThis = makeRef(*this)] () mutable {
208 WebProcessProxy::deleteWebsiteDataForTopPrivatelyControlledDomainsInAllPersistentDataStores(WebResourceLoadStatisticsStore::monitoredDataTypes(), WTFMove(prevalentResourceDomains), m_parameters.shouldNotifyPagesWhenDataRecordsWereScanned, [this, protectedThis = WTFMove(protectedThis)](const HashSet<String>& domainsWithDeletedWebsiteData) mutable {
209 m_statisticsQueue->dispatch([this, protectedThis = WTFMove(protectedThis), topDomains = crossThreadCopy(domainsWithDeletedWebsiteData)] () mutable {
210 for (auto& prevalentResourceDomain : topDomains) {
211 auto& statistic = ensureResourceStatisticsForPrimaryDomain(prevalentResourceDomain);
212 ++statistic.dataRecordsRemoved;
214 setDataRecordsBeingRemoved(false);
220 void WebResourceLoadStatisticsStore::scheduleStatisticsAndDataRecordsProcessing()
222 ASSERT(RunLoop::isMain());
223 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
224 processStatisticsAndDataRecords();
228 void WebResourceLoadStatisticsStore::processStatisticsAndDataRecords()
230 ASSERT(!RunLoop::isMain());
232 if (m_parameters.shouldClassifyResourcesBeforeDataRecordsRemoval) {
233 for (auto& resourceStatistic : m_resourceStatisticsMap.values()) {
234 if (!resourceStatistic.isPrevalentResource && m_resourceLoadStatisticsClassifier.hasPrevalentResourceCharacteristics(resourceStatistic))
235 resourceStatistic.isPrevalentResource = true;
240 pruneStatisticsIfNeeded();
242 if (m_parameters.shouldNotifyPagesWhenDataRecordsWereScanned) {
243 RunLoop::main().dispatch([] {
244 WebProcessProxy::notifyPageStatisticsAndDataRecordsProcessed();
248 m_persistentStorage.scheduleOrWriteMemoryStore(ResourceLoadStatisticsPersistentStorage::ForceImmediateWrite::No);
251 void WebResourceLoadStatisticsStore::resourceLoadStatisticsUpdated(Vector<WebCore::ResourceLoadStatistics>&& origins)
253 ASSERT(!RunLoop::isMain());
255 mergeStatistics(WTFMove(origins));
256 // Fire before processing statistics to propagate user interaction as fast as possible to the network process.
257 updateCookiePartitioning();
258 processStatisticsAndDataRecords();
261 void WebResourceLoadStatisticsStore::hasStorageAccess(String&& subFrameHost, String&& topFrameHost, uint64_t frameID, uint64_t pageID, WTF::CompletionHandler<void (bool)>&& callback)
263 ASSERT(subFrameHost != topFrameHost);
264 ASSERT(RunLoop::isMain());
266 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), subFramePrimaryDomain = isolatedPrimaryDomain(subFrameHost), topFramePrimaryDomain = isolatedPrimaryDomain(topFrameHost), frameID, pageID, callback = WTFMove(callback)] () mutable {
268 auto& subFrameStatistic = ensureResourceStatisticsForPrimaryDomain(subFramePrimaryDomain);
269 if (shouldBlockCookies(subFrameStatistic)) {
274 if (!shouldPartitionCookies(subFrameStatistic)) {
279 m_hasStorageAccessForFrameHandler(subFramePrimaryDomain, topFramePrimaryDomain, frameID, pageID, WTFMove(callback));
283 void WebResourceLoadStatisticsStore::requestStorageAccess(String&& subFrameHost, String&& topFrameHost, uint64_t frameID, uint64_t pageID, WTF::CompletionHandler<void (bool)>&& callback)
285 ASSERT(subFrameHost != topFrameHost);
286 ASSERT(RunLoop::isMain());
288 auto subFramePrimaryDomain = isolatedPrimaryDomain(subFrameHost);
289 auto topFramePrimaryDomain = isolatedPrimaryDomain(topFrameHost);
290 if (subFramePrimaryDomain == topFramePrimaryDomain) {
295 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), subFramePrimaryDomain = crossThreadCopy(subFramePrimaryDomain), topFramePrimaryDomain = crossThreadCopy(topFramePrimaryDomain), frameID, pageID, callback = WTFMove(callback)] () mutable {
297 auto& subFrameStatistic = ensureResourceStatisticsForPrimaryDomain(subFramePrimaryDomain);
298 if (shouldBlockCookies(subFrameStatistic)) {
303 if (!shouldPartitionCookies(subFrameStatistic)) {
308 m_grantStorageAccessForFrameHandler(subFramePrimaryDomain, topFramePrimaryDomain, frameID, pageID, WTFMove(callback));
312 void WebResourceLoadStatisticsStore::grandfatherExistingWebsiteData(CompletionHandler<void()>&& callback)
314 ASSERT(!RunLoop::isMain());
316 RunLoop::main().dispatch([this, protectedThis = makeRef(*this), callback = WTFMove(callback)] () mutable {
317 // FIXME: This method being a static call on WebProcessProxy is wrong.
318 // It should be on the data store that this object belongs to.
319 WebProcessProxy::topPrivatelyControlledDomainsWithWebsiteData(WebResourceLoadStatisticsStore::monitoredDataTypes(), m_parameters.shouldNotifyPagesWhenDataRecordsWereScanned, [this, protectedThis = WTFMove(protectedThis), callback = WTFMove(callback)] (HashSet<String>&& topPrivatelyControlledDomainsWithWebsiteData) mutable {
320 m_statisticsQueue->dispatch([this, protectedThis = WTFMove(protectedThis), topDomains = crossThreadCopy(topPrivatelyControlledDomainsWithWebsiteData), callback = WTFMove(callback)] () mutable {
321 for (auto& topPrivatelyControlledDomain : topDomains) {
322 auto& statistic = ensureResourceStatisticsForPrimaryDomain(topPrivatelyControlledDomain);
323 statistic.grandfathered = true;
325 m_endOfGrandfatheringTimestamp = WallTime::now() + m_parameters.grandfatheringTime;
326 m_persistentStorage.scheduleOrWriteMemoryStore(ResourceLoadStatisticsPersistentStorage::ForceImmediateWrite::Yes);
328 logTestingEvent(ASCIILiteral("Grandfathered"));
334 void WebResourceLoadStatisticsStore::processWillOpenConnection(WebProcessProxy&, IPC::Connection& connection)
336 connection.addWorkQueueMessageReceiver(Messages::WebResourceLoadStatisticsStore::messageReceiverName(), m_statisticsQueue.get(), this);
339 void WebResourceLoadStatisticsStore::processDidCloseConnection(WebProcessProxy&, IPC::Connection& connection)
341 connection.removeWorkQueueMessageReceiver(Messages::WebResourceLoadStatisticsStore::messageReceiverName());
344 void WebResourceLoadStatisticsStore::applicationWillTerminate()
346 m_persistentStorage.finishAllPendingWorkSynchronously();
349 void WebResourceLoadStatisticsStore::performDailyTasks()
351 ASSERT(RunLoop::isMain());
353 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
354 includeTodayAsOperatingDateIfNecessary();
356 if (m_parameters.shouldSubmitTelemetry)
360 void WebResourceLoadStatisticsStore::submitTelemetry()
362 ASSERT(RunLoop::isMain());
363 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
364 WebResourceLoadStatisticsTelemetry::calculateAndSubmit(*this);
368 void WebResourceLoadStatisticsStore::setResourceLoadStatisticsDebugMode(bool enable)
371 setTimeToLiveCookiePartitionFree(30_s);
373 resetParametersToDefaultValues();
376 void WebResourceLoadStatisticsStore::logUserInteraction(const URL& url)
378 if (url.isBlankURL() || url.isEmpty())
381 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url)] {
382 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
383 statistics.hadUserInteraction = true;
384 statistics.mostRecentUserInteractionTime = WallTime::now();
386 if (statistics.isMarkedForCookiePartitioning || statistics.isMarkedForCookieBlocking)
387 updateCookiePartitioningForDomains({ }, { }, { primaryDomain }, ShouldClearFirst::No);
391 void WebResourceLoadStatisticsStore::logNonRecentUserInteraction(const URL& url)
393 if (url.isBlankURL() || url.isEmpty())
396 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url)] {
397 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
398 statistics.hadUserInteraction = true;
399 statistics.mostRecentUserInteractionTime = WallTime::now() - (m_parameters.timeToLiveCookiePartitionFree + Seconds::fromHours(1));
401 updateCookiePartitioningForDomains({ primaryDomain }, { }, { }, ShouldClearFirst::No);
405 void WebResourceLoadStatisticsStore::clearUserInteraction(const URL& url)
407 if (url.isBlankURL() || url.isEmpty())
410 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url)] {
411 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
412 statistics.hadUserInteraction = false;
413 statistics.mostRecentUserInteractionTime = { };
417 void WebResourceLoadStatisticsStore::hasHadUserInteraction(const URL& url, WTF::Function<void (bool)>&& completionHandler)
419 if (url.isBlankURL() || url.isEmpty()) {
420 completionHandler(false);
424 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url), completionHandler = WTFMove(completionHandler)] () mutable {
425 auto mapEntry = m_resourceStatisticsMap.find(primaryDomain);
426 bool hadUserInteraction = mapEntry == m_resourceStatisticsMap.end() ? false: hasHadUnexpiredRecentUserInteraction(mapEntry->value);
427 RunLoop::main().dispatch([hadUserInteraction, completionHandler = WTFMove(completionHandler)] {
428 completionHandler(hadUserInteraction);
433 void WebResourceLoadStatisticsStore::setLastSeen(const URL& url, Seconds seconds)
435 if (url.isBlankURL() || url.isEmpty())
438 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url), seconds] {
439 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
440 statistics.lastSeen = WallTime::fromRawSeconds(seconds.seconds());
444 void WebResourceLoadStatisticsStore::setPrevalentResource(const URL& url)
446 if (url.isBlankURL() || url.isEmpty())
449 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url)] {
450 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
451 statistics.isPrevalentResource = true;
455 void WebResourceLoadStatisticsStore::isPrevalentResource(const URL& url, WTF::Function<void (bool)>&& completionHandler)
457 if (url.isBlankURL() || url.isEmpty()) {
458 completionHandler(false);
462 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url), completionHandler = WTFMove(completionHandler)] () mutable {
463 auto mapEntry = m_resourceStatisticsMap.find(primaryDomain);
464 bool isPrevalentResource = mapEntry == m_resourceStatisticsMap.end() ? false : mapEntry->value.isPrevalentResource;
465 RunLoop::main().dispatch([isPrevalentResource, completionHandler = WTFMove(completionHandler)] {
466 completionHandler(isPrevalentResource);
471 void WebResourceLoadStatisticsStore::isRegisteredAsSubFrameUnder(const URL& subFrame, const URL& topFrame, WTF::Function<void (bool)>&& completionHandler)
473 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), subFramePrimaryDomain = isolatedPrimaryDomain(subFrame), topFramePrimaryDomain = isolatedPrimaryDomain(topFrame), completionHandler = WTFMove(completionHandler)] () mutable {
474 auto mapEntry = m_resourceStatisticsMap.find(subFramePrimaryDomain);
475 bool isRegisteredAsSubFrameUnder = mapEntry == m_resourceStatisticsMap.end() ? false : mapEntry->value.subframeUnderTopFrameOrigins.contains(topFramePrimaryDomain);
476 RunLoop::main().dispatch([isRegisteredAsSubFrameUnder, completionHandler = WTFMove(completionHandler)] {
477 completionHandler(isRegisteredAsSubFrameUnder);
482 void WebResourceLoadStatisticsStore::isRegisteredAsRedirectingTo(const URL& hostRedirectedFrom, const URL& hostRedirectedTo, WTF::Function<void (bool)>&& completionHandler)
484 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), hostRedirectedFromPrimaryDomain = isolatedPrimaryDomain(hostRedirectedFrom), hostRedirectedToPrimaryDomain = isolatedPrimaryDomain(hostRedirectedTo), completionHandler = WTFMove(completionHandler)] () mutable {
485 auto mapEntry = m_resourceStatisticsMap.find(hostRedirectedFromPrimaryDomain);
486 bool isRegisteredAsRedirectingTo = mapEntry == m_resourceStatisticsMap.end() ? false : mapEntry->value.subresourceUniqueRedirectsTo.contains(hostRedirectedToPrimaryDomain);
487 RunLoop::main().dispatch([isRegisteredAsRedirectingTo, completionHandler = WTFMove(completionHandler)] {
488 completionHandler(isRegisteredAsRedirectingTo);
493 void WebResourceLoadStatisticsStore::clearPrevalentResource(const URL& url)
495 if (url.isBlankURL() || url.isEmpty())
498 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url)] {
499 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
500 statistics.isPrevalentResource = false;
504 void WebResourceLoadStatisticsStore::setGrandfathered(const URL& url, bool value)
506 if (url.isBlankURL() || url.isEmpty())
509 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryDomain = isolatedPrimaryDomain(url), value] {
510 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primaryDomain);
511 statistics.grandfathered = value;
515 void WebResourceLoadStatisticsStore::isGrandfathered(const URL& url, WTF::Function<void (bool)>&& completionHandler)
517 if (url.isBlankURL() || url.isEmpty()) {
518 completionHandler(false);
522 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler), primaryDomain = isolatedPrimaryDomain(url)] () mutable {
523 auto mapEntry = m_resourceStatisticsMap.find(primaryDomain);
524 bool isGrandFathered = mapEntry == m_resourceStatisticsMap.end() ? false : mapEntry->value.grandfathered;
525 RunLoop::main().dispatch([isGrandFathered, completionHandler = WTFMove(completionHandler)] {
526 completionHandler(isGrandFathered);
531 void WebResourceLoadStatisticsStore::setSubframeUnderTopFrameOrigin(const URL& subframe, const URL& topFrame)
533 if (subframe.isBlankURL() || subframe.isEmpty() || topFrame.isBlankURL() || topFrame.isEmpty())
536 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryTopFrameDomain = isolatedPrimaryDomain(topFrame), primarySubFrameDomain = isolatedPrimaryDomain(subframe)] {
537 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primarySubFrameDomain);
538 statistics.subframeUnderTopFrameOrigins.add(primaryTopFrameDomain);
542 void WebResourceLoadStatisticsStore::setSubresourceUnderTopFrameOrigin(const URL& subresource, const URL& topFrame)
544 if (subresource.isBlankURL() || subresource.isEmpty() || topFrame.isBlankURL() || topFrame.isEmpty())
547 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryTopFrameDomain = isolatedPrimaryDomain(topFrame), primarySubresourceDomain = isolatedPrimaryDomain(subresource)] {
548 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primarySubresourceDomain);
549 statistics.subresourceUnderTopFrameOrigins.add(primaryTopFrameDomain);
553 void WebResourceLoadStatisticsStore::setSubresourceUniqueRedirectTo(const URL& subresource, const URL& hostNameRedirectedTo)
555 if (subresource.isBlankURL() || subresource.isEmpty() || hostNameRedirectedTo.isBlankURL() || hostNameRedirectedTo.isEmpty())
558 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), primaryRedirectDomain = isolatedPrimaryDomain(hostNameRedirectedTo), primarySubresourceDomain = isolatedPrimaryDomain(subresource)] {
559 auto& statistics = ensureResourceStatisticsForPrimaryDomain(primarySubresourceDomain);
560 statistics.subresourceUniqueRedirectsTo.add(primaryRedirectDomain);
564 void WebResourceLoadStatisticsStore::scheduleCookiePartitioningUpdate()
566 // Helper function used by testing system. Should only be called from the main thread.
567 ASSERT(RunLoop::isMain());
569 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
570 updateCookiePartitioning();
574 void WebResourceLoadStatisticsStore::scheduleCookiePartitioningUpdateForDomains(const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, ShouldClearFirst shouldClearFirst)
576 // Helper function used by testing system. Should only be called from the main thread.
577 ASSERT(RunLoop::isMain());
578 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), domainsToPartition = crossThreadCopy(domainsToPartition), domainsToBlock = crossThreadCopy(domainsToBlock), domainsToNeitherPartitionNorBlock = crossThreadCopy(domainsToNeitherPartitionNorBlock), shouldClearFirst] {
579 updateCookiePartitioningForDomains(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst);
583 void WebResourceLoadStatisticsStore::scheduleClearPartitioningStateForDomains(const Vector<String>& domains)
585 // Helper function used by testing system. Should only be called from the main thread.
586 ASSERT(RunLoop::isMain());
587 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), domains = crossThreadCopy(domains)] {
588 clearPartitioningStateForDomains(domains);
592 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
593 void WebResourceLoadStatisticsStore::scheduleCookiePartitioningStateReset()
595 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
596 resetCookiePartitioningState();
601 void WebResourceLoadStatisticsStore::scheduleClearInMemory()
603 ASSERT(RunLoop::isMain());
604 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
609 void WebResourceLoadStatisticsStore::scheduleClearInMemoryAndPersistent(ShouldGrandfather shouldGrandfather, CompletionHandler<void()>&& callback)
611 ASSERT(RunLoop::isMain());
612 m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this), shouldGrandfather, callback = WTFMove(callback)] () mutable {
614 m_persistentStorage.clear();
616 if (shouldGrandfather == ShouldGrandfather::Yes)
617 grandfatherExistingWebsiteData([protectedThis = makeRef(*this), callback = WTFMove(callback)]() {
626 void WebResourceLoadStatisticsStore::scheduleClearInMemoryAndPersistent(WallTime modifiedSince, ShouldGrandfather shouldGrandfather, CompletionHandler<void()>&& callback)
628 // For now, be conservative and clear everything regardless of modifiedSince.
629 UNUSED_PARAM(modifiedSince);
630 scheduleClearInMemoryAndPersistent(shouldGrandfather, WTFMove(callback));
633 void WebResourceLoadStatisticsStore::setTimeToLiveUserInteraction(Seconds seconds)
635 ASSERT(seconds >= 0_s);
636 m_parameters.timeToLiveUserInteraction = seconds;
639 void WebResourceLoadStatisticsStore::setTimeToLiveCookiePartitionFree(Seconds seconds)
641 ASSERT(seconds >= 0_s);
642 m_parameters.timeToLiveCookiePartitionFree = seconds;
645 void WebResourceLoadStatisticsStore::setMinimumTimeBetweenDataRecordsRemoval(Seconds seconds)
647 ASSERT(seconds >= 0_s);
648 m_parameters.minimumTimeBetweenDataRecordsRemoval = seconds;
651 void WebResourceLoadStatisticsStore::setGrandfatheringTime(Seconds seconds)
653 ASSERT(seconds >= 0_s);
654 m_parameters.grandfatheringTime = seconds;
657 bool WebResourceLoadStatisticsStore::shouldRemoveDataRecords() const
659 ASSERT(!RunLoop::isMain());
660 if (m_dataRecordsBeingRemoved)
663 #if ENABLE(NETSCAPE_PLUGIN_API)
664 for (auto plugin : PluginProcessManager::singleton().pluginProcesses()) {
665 if (!m_activePluginTokens.contains(plugin->pluginProcessToken()))
670 return !m_lastTimeDataRecordsWereRemoved || MonotonicTime::now() >= (m_lastTimeDataRecordsWereRemoved + m_parameters.minimumTimeBetweenDataRecordsRemoval);
673 void WebResourceLoadStatisticsStore::setDataRecordsBeingRemoved(bool value)
675 ASSERT(!RunLoop::isMain());
676 m_dataRecordsBeingRemoved = value;
677 if (m_dataRecordsBeingRemoved)
678 m_lastTimeDataRecordsWereRemoved = MonotonicTime::now();
681 ResourceLoadStatistics& WebResourceLoadStatisticsStore::ensureResourceStatisticsForPrimaryDomain(const String& primaryDomain)
683 ASSERT(!RunLoop::isMain());
684 return m_resourceStatisticsMap.ensure(primaryDomain, [&primaryDomain] {
685 return ResourceLoadStatistics(primaryDomain);
689 std::unique_ptr<KeyedEncoder> WebResourceLoadStatisticsStore::createEncoderFromData() const
691 ASSERT(!RunLoop::isMain());
692 auto encoder = KeyedEncoder::encoder();
693 encoder->encodeUInt32("version", statisticsModelVersion);
694 encoder->encodeDouble("endOfGrandfatheringTimestamp", m_endOfGrandfatheringTimestamp.secondsSinceEpoch().value());
696 encoder->encodeObjects("browsingStatistics", m_resourceStatisticsMap.begin(), m_resourceStatisticsMap.end(), [](KeyedEncoder& encoderInner, const auto& origin) {
697 origin.value.encode(encoderInner);
700 encoder->encodeObjects("operatingDates", m_operatingDates.begin(), m_operatingDates.end(), [](KeyedEncoder& encoderInner, OperatingDate date) {
701 encoderInner.encodeDouble("date", date.secondsSinceEpoch().value());
707 void WebResourceLoadStatisticsStore::mergeWithDataFromDecoder(KeyedDecoder& decoder)
709 ASSERT(!RunLoop::isMain());
711 unsigned versionOnDisk;
712 if (!decoder.decodeUInt32("version", versionOnDisk))
715 if (versionOnDisk != statisticsModelVersion)
718 double endOfGrandfatheringTimestamp;
719 if (decoder.decodeDouble("endOfGrandfatheringTimestamp", endOfGrandfatheringTimestamp))
720 m_endOfGrandfatheringTimestamp = WallTime::fromRawSeconds(endOfGrandfatheringTimestamp);
722 m_endOfGrandfatheringTimestamp = { };
724 Vector<ResourceLoadStatistics> loadedStatistics;
725 bool succeeded = decoder.decodeObjects("browsingStatistics", loadedStatistics, [](KeyedDecoder& decoderInner, ResourceLoadStatistics& statistics) {
726 return statistics.decode(decoderInner);
732 mergeStatistics(WTFMove(loadedStatistics));
733 updateCookiePartitioning();
735 Vector<OperatingDate> operatingDates;
736 succeeded = decoder.decodeObjects("operatingDates", operatingDates, [](KeyedDecoder& decoder, OperatingDate& date) {
738 if (!decoder.decodeDouble("date", value))
741 date = OperatingDate::fromWallTime(WallTime::fromRawSeconds(value));
748 m_operatingDates = mergeOperatingDates(m_operatingDates, WTFMove(operatingDates));
751 void WebResourceLoadStatisticsStore::clearInMemory()
753 ASSERT(!RunLoop::isMain());
754 m_resourceStatisticsMap.clear();
755 m_operatingDates.clear();
757 updateCookiePartitioningForDomains({ }, { }, { }, ShouldClearFirst::Yes);
760 void WebResourceLoadStatisticsStore::mergeStatistics(Vector<ResourceLoadStatistics>&& statistics)
762 ASSERT(!RunLoop::isMain());
763 for (auto& statistic : statistics) {
764 auto result = m_resourceStatisticsMap.ensure(statistic.highLevelDomain, [&statistic] {
765 return WTFMove(statistic);
767 if (!result.isNewEntry)
768 result.iterator->value.merge(statistic);
772 bool WebResourceLoadStatisticsStore::shouldPartitionCookies(const ResourceLoadStatistics& statistic) const
774 return statistic.isPrevalentResource && statistic.hadUserInteraction && WallTime::now() > statistic.mostRecentUserInteractionTime + m_parameters.timeToLiveCookiePartitionFree;
777 bool WebResourceLoadStatisticsStore::shouldBlockCookies(const ResourceLoadStatistics& statistic) const
779 return statistic.isPrevalentResource && !statistic.hadUserInteraction;
782 void WebResourceLoadStatisticsStore::updateCookiePartitioning()
784 ASSERT(!RunLoop::isMain());
786 Vector<String> domainsToPartition;
787 Vector<String> domainsToBlock;
788 Vector<String> domainsToNeitherPartitionNorBlock;
789 for (auto& resourceStatistic : m_resourceStatisticsMap.values()) {
791 bool shouldPartition = shouldPartitionCookies(resourceStatistic);
792 bool shouldBlock = shouldBlockCookies(resourceStatistic);
794 if (shouldPartition && !resourceStatistic.isMarkedForCookiePartitioning) {
795 domainsToPartition.append(resourceStatistic.highLevelDomain);
796 resourceStatistic.isMarkedForCookiePartitioning = true;
797 } else if (shouldBlock && !resourceStatistic.isMarkedForCookieBlocking) {
798 domainsToBlock.append(resourceStatistic.highLevelDomain);
799 resourceStatistic.isMarkedForCookieBlocking = true;
800 } else if (!shouldPartition && !shouldBlock && resourceStatistic.isPrevalentResource) {
801 domainsToNeitherPartitionNorBlock.append(resourceStatistic.highLevelDomain);
802 resourceStatistic.isMarkedForCookiePartitioning = false;
803 resourceStatistic.isMarkedForCookieBlocking = false;
807 if (domainsToPartition.isEmpty() && domainsToBlock.isEmpty() && domainsToNeitherPartitionNorBlock.isEmpty())
810 RunLoop::main().dispatch([this, protectedThis = makeRef(*this), domainsToPartition = crossThreadCopy(domainsToPartition), domainsToBlock = crossThreadCopy(domainsToBlock), domainsToNeitherPartitionNorBlock = crossThreadCopy(domainsToNeitherPartitionNorBlock)] () {
811 m_updatePrevalentDomainsToPartitionOrBlockCookiesHandler(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, ShouldClearFirst::No);
815 void WebResourceLoadStatisticsStore::updateCookiePartitioningForDomains(const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, ShouldClearFirst shouldClearFirst)
817 ASSERT(!RunLoop::isMain());
818 if (domainsToPartition.isEmpty() && domainsToBlock.isEmpty() && domainsToNeitherPartitionNorBlock.isEmpty() && shouldClearFirst == ShouldClearFirst::No)
821 RunLoop::main().dispatch([this, shouldClearFirst, protectedThis = makeRef(*this), domainsToPartition = crossThreadCopy(domainsToPartition), domainsToBlock = crossThreadCopy(domainsToBlock), domainsToNeitherPartitionNorBlock = crossThreadCopy(domainsToNeitherPartitionNorBlock)] () {
822 m_updatePrevalentDomainsToPartitionOrBlockCookiesHandler(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst);
825 if (shouldClearFirst == ShouldClearFirst::Yes)
826 resetCookiePartitioningState();
828 for (auto& domain : domainsToNeitherPartitionNorBlock) {
829 auto& statistic = ensureResourceStatisticsForPrimaryDomain(domain);
830 statistic.isMarkedForCookiePartitioning = false;
831 statistic.isMarkedForCookieBlocking = false;
835 for (auto& domain : domainsToPartition)
836 ensureResourceStatisticsForPrimaryDomain(domain).isMarkedForCookiePartitioning = true;
838 for (auto& domain : domainsToBlock)
839 ensureResourceStatisticsForPrimaryDomain(domain).isMarkedForCookieBlocking = true;
842 void WebResourceLoadStatisticsStore::clearPartitioningStateForDomains(const Vector<String>& domains)
844 ASSERT(!RunLoop::isMain());
845 if (domains.isEmpty())
848 RunLoop::main().dispatch([this, protectedThis = makeRef(*this), domains = crossThreadCopy(domains)] () {
849 m_removeDomainsHandler(domains);
852 for (auto& domain : domains) {
853 auto& statistic = ensureResourceStatisticsForPrimaryDomain(domain);
854 statistic.isMarkedForCookiePartitioning = false;
855 statistic.isMarkedForCookieBlocking = false;
859 void WebResourceLoadStatisticsStore::resetCookiePartitioningState()
861 ASSERT(!RunLoop::isMain());
862 for (auto& resourceStatistic : m_resourceStatisticsMap.values()) {
863 resourceStatistic.isMarkedForCookiePartitioning = false;
864 resourceStatistic.isMarkedForCookieBlocking = false;
868 void WebResourceLoadStatisticsStore::processStatistics(const WTF::Function<void (const ResourceLoadStatistics&)>& processFunction) const
870 ASSERT(!RunLoop::isMain());
871 for (auto& resourceStatistic : m_resourceStatisticsMap.values())
872 processFunction(resourceStatistic);
875 bool WebResourceLoadStatisticsStore::hasHadUnexpiredRecentUserInteraction(ResourceLoadStatistics& resourceStatistic) const
877 if (resourceStatistic.hadUserInteraction && hasStatisticsExpired(resourceStatistic)) {
878 // Drop privacy sensitive data because we no longer need it.
879 // Set timestamp to 0 so that statistics merge will know
880 // it has been reset as opposed to its default -1.
881 resourceStatistic.mostRecentUserInteractionTime = { };
882 resourceStatistic.hadUserInteraction = false;
885 return resourceStatistic.hadUserInteraction;
888 Vector<String> WebResourceLoadStatisticsStore::topPrivatelyControlledDomainsToRemoveWebsiteDataFor()
890 ASSERT(!RunLoop::isMain());
892 bool shouldCheckForGrandfathering = m_endOfGrandfatheringTimestamp > WallTime::now();
893 bool shouldClearGrandfathering = !shouldCheckForGrandfathering && m_endOfGrandfatheringTimestamp;
895 if (shouldClearGrandfathering)
896 m_endOfGrandfatheringTimestamp = { };
898 Vector<String> prevalentResources;
899 for (auto& statistic : m_resourceStatisticsMap.values()) {
900 if (statistic.isPrevalentResource && !hasHadUnexpiredRecentUserInteraction(statistic) && (!shouldCheckForGrandfathering || !statistic.grandfathered))
901 prevalentResources.append(statistic.highLevelDomain);
903 if (shouldClearGrandfathering && statistic.grandfathered)
904 statistic.grandfathered = false;
907 return prevalentResources;
910 void WebResourceLoadStatisticsStore::includeTodayAsOperatingDateIfNecessary()
912 ASSERT(!RunLoop::isMain());
914 auto today = OperatingDate::today();
915 if (!m_operatingDates.isEmpty() && today <= m_operatingDates.last())
918 while (m_operatingDates.size() >= operatingDatesWindow)
919 m_operatingDates.remove(0);
921 m_operatingDates.append(today);
924 bool WebResourceLoadStatisticsStore::hasStatisticsExpired(const ResourceLoadStatistics& resourceStatistic) const
926 if (m_operatingDates.size() >= operatingDatesWindow) {
927 if (OperatingDate::fromWallTime(resourceStatistic.mostRecentUserInteractionTime) < m_operatingDates.first())
931 // If we don't meet the real criteria for an expired statistic, check the user setting for a tighter restriction (mainly for testing).
932 if (m_parameters.timeToLiveUserInteraction) {
933 if (WallTime::now() > resourceStatistic.mostRecentUserInteractionTime + m_parameters.timeToLiveUserInteraction.value())
940 void WebResourceLoadStatisticsStore::setMaxStatisticsEntries(size_t maximumEntryCount)
942 m_parameters.maxStatisticsEntries = maximumEntryCount;
945 void WebResourceLoadStatisticsStore::setPruneEntriesDownTo(size_t pruneTargetCount)
947 m_parameters.pruneEntriesDownTo = pruneTargetCount;
950 struct StatisticsLastSeen {
951 String topPrivatelyOwnedDomain;
955 static void pruneResources(HashMap<String, WebCore::ResourceLoadStatistics>& statisticsMap, Vector<StatisticsLastSeen>& statisticsToPrune, size_t& numberOfEntriesToPrune)
957 if (statisticsToPrune.size() > numberOfEntriesToPrune) {
958 std::sort(statisticsToPrune.begin(), statisticsToPrune.end(), [](const StatisticsLastSeen& a, const StatisticsLastSeen& b) {
959 return a.lastSeen < b.lastSeen;
963 for (size_t i = 0, end = std::min(numberOfEntriesToPrune, statisticsToPrune.size()); i != end; ++i, --numberOfEntriesToPrune)
964 statisticsMap.remove(statisticsToPrune[i].topPrivatelyOwnedDomain);
967 static unsigned computeImportance(const ResourceLoadStatistics& resourceStatistic)
969 unsigned importance = maxImportance;
970 if (!resourceStatistic.isPrevalentResource)
972 if (!resourceStatistic.hadUserInteraction)
977 void WebResourceLoadStatisticsStore::pruneStatisticsIfNeeded()
979 ASSERT(!RunLoop::isMain());
980 if (m_resourceStatisticsMap.size() <= m_parameters.maxStatisticsEntries)
983 ASSERT(m_parameters.pruneEntriesDownTo <= m_parameters.maxStatisticsEntries);
985 size_t numberOfEntriesLeftToPrune = m_resourceStatisticsMap.size() - m_parameters.pruneEntriesDownTo;
986 ASSERT(numberOfEntriesLeftToPrune);
988 Vector<StatisticsLastSeen> resourcesToPrunePerImportance[maxImportance + 1];
989 for (auto& resourceStatistic : m_resourceStatisticsMap.values())
990 resourcesToPrunePerImportance[computeImportance(resourceStatistic)].append({ resourceStatistic.highLevelDomain, resourceStatistic.lastSeen });
992 for (unsigned importance = 0; numberOfEntriesLeftToPrune && importance <= maxImportance; ++importance)
993 pruneResources(m_resourceStatisticsMap, resourcesToPrunePerImportance[importance], numberOfEntriesLeftToPrune);
995 ASSERT(!numberOfEntriesLeftToPrune);
998 void WebResourceLoadStatisticsStore::resetParametersToDefaultValues()
1003 void WebResourceLoadStatisticsStore::logTestingEvent(const String& event)
1005 if (!m_statisticsTestingCallback)
1008 if (RunLoop::isMain())
1009 m_statisticsTestingCallback(event);
1011 RunLoop::main().dispatch([this, protectedThis = makeRef(*this), event = event.isolatedCopy()] {
1012 if (m_statisticsTestingCallback)
1013 m_statisticsTestingCallback(event);
1018 } // namespace WebKit