1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
|
/*
* Copyright (C) 2016-2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebResourceLoadStatisticsStore.h"
#include "WebProcessMessages.h"
#include "WebProcessPool.h"
#include "WebProcessProxy.h"
#include "WebResourceLoadStatisticsStoreMessages.h"
#include "WebsiteDataFetchOption.h"
#include "WebsiteDataType.h"
#include <WebCore/KeyedCoding.h>
#include <WebCore/ResourceLoadObserver.h>
#include <WebCore/ResourceLoadStatistics.h>
#include <wtf/CurrentTime.h>
#include <wtf/MainThread.h>
#include <wtf/MathExtras.h>
#include <wtf/RunLoop.h>
#include <wtf/threads/BinarySemaphore.h>
using namespace WebCore;
namespace WebKit {
static const auto featureVectorLengthThreshold = 3;
static auto minimumTimeBetweeenDataRecordsRemoval = 60;
static OptionSet<WebKit::WebsiteDataType> dataTypesToRemove;
static auto notifyPages = false;
static auto shouldClassifyResourcesBeforeDataRecordsRemoval = true;
Ref<WebResourceLoadStatisticsStore> WebResourceLoadStatisticsStore::create(const String& resourceLoadStatisticsDirectory)
{
return adoptRef(*new WebResourceLoadStatisticsStore(resourceLoadStatisticsDirectory));
}
WebResourceLoadStatisticsStore::WebResourceLoadStatisticsStore(const String& resourceLoadStatisticsDirectory)
: m_resourceLoadStatisticsStore(ResourceLoadStatisticsStore::create())
, m_statisticsQueue(WorkQueue::create("WebResourceLoadStatisticsStore Process Data Queue"))
, m_storagePath(resourceLoadStatisticsDirectory)
{
}
WebResourceLoadStatisticsStore::~WebResourceLoadStatisticsStore()
{
}
void WebResourceLoadStatisticsStore::setNotifyPagesWhenDataRecordsWereScanned(bool always)
{
notifyPages = always;
}
void WebResourceLoadStatisticsStore::setShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
{
shouldClassifyResourcesBeforeDataRecordsRemoval = value;
}
void WebResourceLoadStatisticsStore::setMinimumTimeBetweeenDataRecordsRemoval(double seconds)
{
if (seconds >= 0)
minimumTimeBetweeenDataRecordsRemoval = seconds;
}
bool WebResourceLoadStatisticsStore::hasPrevalentResourceCharacteristics(const ResourceLoadStatistics& resourceStatistic)
{
auto subresourceUnderTopFrameOriginsCount = resourceStatistic.subresourceUnderTopFrameOrigins.size();
auto subresourceUniqueRedirectsToCount = resourceStatistic.subresourceUniqueRedirectsTo.size();
auto subframeUnderTopFrameOriginsCount = resourceStatistic.subframeUnderTopFrameOrigins.size();
if (!subresourceUnderTopFrameOriginsCount
&& !subresourceUniqueRedirectsToCount
&& !subframeUnderTopFrameOriginsCount)
return false;
if (subresourceUnderTopFrameOriginsCount > featureVectorLengthThreshold
|| subresourceUniqueRedirectsToCount > featureVectorLengthThreshold
|| subframeUnderTopFrameOriginsCount > featureVectorLengthThreshold)
return true;
// The resource is considered prevalent if the feature vector
// is longer than the threshold.
// Vector length for n dimensions is sqrt(a^2 + (...) + n^2).
double vectorLength = 0;
vectorLength += subresourceUnderTopFrameOriginsCount * subresourceUnderTopFrameOriginsCount;
vectorLength += subresourceUniqueRedirectsToCount * subresourceUniqueRedirectsToCount;
vectorLength += subframeUnderTopFrameOriginsCount * subframeUnderTopFrameOriginsCount;
ASSERT(vectorLength > 0);
return sqrt(vectorLength) > featureVectorLengthThreshold;
}
void WebResourceLoadStatisticsStore::classifyResource(ResourceLoadStatistics& resourceStatistic)
{
if (!resourceStatistic.isPrevalentResource && hasPrevalentResourceCharacteristics(resourceStatistic)) {
resourceStatistic.isPrevalentResource = true;
}
}
void WebResourceLoadStatisticsStore::removeDataRecords()
{
if (m_dataRecordsRemovalPending)
return;
Vector<String> prevalentResourceDomains = coreStore().prevalentResourceDomainsWithoutUserInteraction();
if (!prevalentResourceDomains.size())
return;
double now = currentTime();
if (m_lastTimeDataRecordsWereRemoved
&& now < m_lastTimeDataRecordsWereRemoved + minimumTimeBetweeenDataRecordsRemoval)
return;
m_dataRecordsRemovalPending = true;
m_lastTimeDataRecordsWereRemoved = now;
if (dataTypesToRemove.isEmpty()) {
dataTypesToRemove |= WebsiteDataType::Cookies;
dataTypesToRemove |= WebsiteDataType::DiskCache;
dataTypesToRemove |= WebsiteDataType::MemoryCache;
dataTypesToRemove |= WebsiteDataType::OfflineWebApplicationCache;
dataTypesToRemove |= WebsiteDataType::SessionStorage;
dataTypesToRemove |= WebsiteDataType::LocalStorage;
dataTypesToRemove |= WebsiteDataType::WebSQLDatabases;
dataTypesToRemove |= WebsiteDataType::IndexedDBDatabases;
dataTypesToRemove |= WebsiteDataType::MediaKeys;
dataTypesToRemove |= WebsiteDataType::HSTSCache;
dataTypesToRemove |= WebsiteDataType::SearchFieldRecentSearches;
#if ENABLE(NETSCAPE_PLUGIN_API)
dataTypesToRemove |= WebsiteDataType::PlugInData;
#endif
#if ENABLE(MEDIA_STREAM)
dataTypesToRemove |= WebsiteDataType::MediaDeviceIdentifier;
#endif
}
// Switch to the main thread to get the default website data store
RunLoop::main().dispatch([prevalentResourceDomains = WTFMove(prevalentResourceDomains), this] () mutable {
WebProcessProxy::deleteWebsiteDataForTopPrivatelyOwnedDomainsInAllPersistentDataStores(dataTypesToRemove, prevalentResourceDomains, notifyPages, [this]() mutable {
m_dataRecordsRemovalPending = false;
});
});
}
void WebResourceLoadStatisticsStore::processStatisticsAndDataRecords()
{
if (shouldClassifyResourcesBeforeDataRecordsRemoval) {
coreStore().processStatistics([this] (ResourceLoadStatistics& resourceStatistic) {
classifyResource(resourceStatistic);
});
}
removeDataRecords();
auto encoder = coreStore().createEncoderFromData();
writeEncoderToDisk(*encoder.get(), "full_browsing_session");
}
void WebResourceLoadStatisticsStore::resourceLoadStatisticsUpdated(const Vector<WebCore::ResourceLoadStatistics>& origins)
{
coreStore().mergeStatistics(origins);
processStatisticsAndDataRecords();
}
void WebResourceLoadStatisticsStore::setResourceLoadStatisticsEnabled(bool enabled)
{
if (enabled == m_resourceLoadStatisticsEnabled)
return;
m_resourceLoadStatisticsEnabled = enabled;
readDataFromDiskIfNeeded();
}
bool WebResourceLoadStatisticsStore::resourceLoadStatisticsEnabled() const
{
return m_resourceLoadStatisticsEnabled;
}
void WebResourceLoadStatisticsStore::registerSharedResourceLoadObserver()
{
ResourceLoadObserver::sharedObserver().setStatisticsStore(m_resourceLoadStatisticsStore.copyRef());
m_resourceLoadStatisticsStore->setNotificationCallback([this] {
if (m_resourceLoadStatisticsStore->isEmpty())
return;
processStatisticsAndDataRecords();
});
}
void WebResourceLoadStatisticsStore::readDataFromDiskIfNeeded()
{
if (!m_resourceLoadStatisticsEnabled)
return;
m_statisticsQueue->dispatch([this, protectedThis = makeRef(*this)] {
coreStore().clear();
auto decoder = createDecoderFromDisk("full_browsing_session");
if (!decoder)
return;
coreStore().readDataFromDecoder(*decoder);
});
}
void WebResourceLoadStatisticsStore::processWillOpenConnection(WebProcessProxy&, IPC::Connection& connection)
{
connection.addWorkQueueMessageReceiver(Messages::WebResourceLoadStatisticsStore::messageReceiverName(), m_statisticsQueue.get(), this);
}
void WebResourceLoadStatisticsStore::processDidCloseConnection(WebProcessProxy&, IPC::Connection& connection)
{
connection.removeWorkQueueMessageReceiver(Messages::WebResourceLoadStatisticsStore::messageReceiverName());
}
void WebResourceLoadStatisticsStore::applicationWillTerminate()
{
BinarySemaphore semaphore;
m_statisticsQueue->dispatch([this, &semaphore] {
// Make sure any ongoing work in our queue is finished before we terminate.
semaphore.signal();
});
semaphore.wait(WallTime::infinity());
}
String WebResourceLoadStatisticsStore::persistentStoragePath(const String& label) const
{
if (m_storagePath.isEmpty())
return emptyString();
// TODO Decide what to call this file
return pathByAppendingComponent(m_storagePath, label + "_resourceLog.plist");
}
void WebResourceLoadStatisticsStore::writeEncoderToDisk(KeyedEncoder& encoder, const String& label) const
{
RefPtr<SharedBuffer> rawData = encoder.finishEncoding();
if (!rawData)
return;
String resourceLog = persistentStoragePath(label);
if (resourceLog.isEmpty())
return;
if (!m_storagePath.isEmpty())
makeAllDirectories(m_storagePath);
auto handle = openFile(resourceLog, OpenForWrite);
if (!handle)
return;
int64_t writtenBytes = writeToFile(handle, rawData->data(), rawData->size());
closeFile(handle);
if (writtenBytes != static_cast<int64_t>(rawData->size()))
WTFLogAlways("WebResourceLoadStatisticsStore: We only wrote %d out of %d bytes to disk", static_cast<unsigned>(writtenBytes), rawData->size());
}
std::unique_ptr<KeyedDecoder> WebResourceLoadStatisticsStore::createDecoderFromDisk(const String& label) const
{
String resourceLog = persistentStoragePath(label);
if (resourceLog.isEmpty())
return nullptr;
RefPtr<SharedBuffer> rawData = SharedBuffer::createWithContentsOfFile(resourceLog);
if (!rawData)
return nullptr;
return KeyedDecoder::decoder(reinterpret_cast<const uint8_t*>(rawData->data()), rawData->size());
}
} // namespace WebKit
|