cefcf66ba49abaa9e14640eae0708fcb4eb0f0f7
[WebKit.git] / Source / WebKit / NetworkProcess / cache / NetworkCache.cpp
1 /*
2  * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25
26 #include "config.h"
27 #include "NetworkCache.h"
28
29 #include "Logging.h"
30 #include "NetworkCacheSpeculativeLoadManager.h"
31 #include "NetworkCacheStatistics.h"
32 #include "NetworkCacheStorage.h"
33 #include <WebCore/CacheValidation.h>
34 #include <WebCore/FileSystem.h>
35 #include <WebCore/HTTPHeaderNames.h>
36 #include <WebCore/LowPowerModeNotifier.h>
37 #include <WebCore/NetworkStorageSession.h>
38 #include <WebCore/PlatformCookieJar.h>
39 #include <WebCore/ResourceRequest.h>
40 #include <WebCore/ResourceResponse.h>
41 #include <WebCore/SharedBuffer.h>
42 #include <wtf/MainThread.h>
43 #include <wtf/NeverDestroyed.h>
44 #include <wtf/RunLoop.h>
45 #include <wtf/text/StringBuilder.h>
46
47 #if PLATFORM(COCOA)
48 #include <notify.h>
49 #endif
50
51 using namespace std::literals::chrono_literals;
52 using namespace WebCore::FileSystem;
53
54 namespace WebKit {
55 namespace NetworkCache {
56
57 static const AtomicString& resourceType()
58 {
59     ASSERT(WTF::RunLoop::isMain());
60     static NeverDestroyed<const AtomicString> resource("Resource", AtomicString::ConstructFromLiteral);
61     return resource;
62 }
63
64 RefPtr<Cache> Cache::open(const String& cachePath, OptionSet<Option> options)
65 {
66     auto storage = Storage::open(cachePath, options.contains(Option::TestingMode) ? Storage::Mode::Testing : Storage::Mode::Normal);
67
68     LOG(NetworkCache, "(NetworkProcess) opened cache storage, success %d", !!storage);
69
70     if (!storage)
71         return nullptr;
72
73     return adoptRef(*new Cache(storage.releaseNonNull(), options));
74 }
75
76 #if PLATFORM(GTK)
77 static void dumpFileChanged(Cache* cache)
78 {
79     cache->dumpContentsToFile();
80 }
81 #endif
82
83 Cache::Cache(Ref<Storage>&& storage, OptionSet<Option> options)
84     : m_storage(WTFMove(storage))
85 {
86 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
87     if (options.contains(Option::SpeculativeRevalidation)) {
88         m_lowPowerModeNotifier = std::make_unique<WebCore::LowPowerModeNotifier>([this](bool isLowPowerModeEnabled) {
89             ASSERT(WTF::RunLoop::isMain());
90             if (isLowPowerModeEnabled)
91                 m_speculativeLoadManager = nullptr;
92             else {
93                 ASSERT(!m_speculativeLoadManager);
94                 m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*this, m_storage.get());
95             }
96         });
97         if (!m_lowPowerModeNotifier->isLowPowerModeEnabled())
98             m_speculativeLoadManager = std::make_unique<SpeculativeLoadManager>(*this, m_storage.get());
99     }
100 #endif
101
102     if (options.contains(Option::EfficacyLogging))
103         m_statistics = Statistics::open(*this, m_storage->basePath());
104
105     if (options.contains(Option::RegisterNotify)) {
106 #if PLATFORM(COCOA)
107         // Triggers with "notifyutil -p com.apple.WebKit.Cache.dump".
108         int token;
109         notify_register_dispatch("com.apple.WebKit.Cache.dump", &token, dispatch_get_main_queue(), ^(int) {
110             dumpContentsToFile();
111         });
112 #endif
113 #if PLATFORM(GTK)
114         // Triggers with "touch $cachePath/dump".
115         CString dumpFilePath = fileSystemRepresentation(pathByAppendingComponent(m_storage->basePath(), "dump"));
116         GRefPtr<GFile> dumpFile = adoptGRef(g_file_new_for_path(dumpFilePath.data()));
117         GFileMonitor* monitor = g_file_monitor_file(dumpFile.get(), G_FILE_MONITOR_NONE, nullptr, nullptr);
118         g_signal_connect_swapped(monitor, "changed", G_CALLBACK(dumpFileChanged), this);
119 #endif
120     }
121 }
122
123 Cache::~Cache()
124 {
125 }
126
127 void Cache::setCapacity(size_t maximumSize)
128 {
129     m_storage->setCapacity(maximumSize);
130 }
131
132 Key Cache::makeCacheKey(const WebCore::ResourceRequest& request)
133 {
134     // FIXME: This implements minimal Range header disk cache support. We don't parse
135     // ranges so only the same exact range request will be served from the cache.
136     String range = request.httpHeaderField(WebCore::HTTPHeaderName::Range);
137     return { request.cachePartition(), resourceType(), range, request.url().string(), m_storage->salt() };
138 }
139
140 static bool cachePolicyAllowsExpired(WebCore::ResourceRequestCachePolicy policy)
141 {
142     switch (policy) {
143     case WebCore::ReturnCacheDataElseLoad:
144     case WebCore::ReturnCacheDataDontLoad:
145         return true;
146     case WebCore::UseProtocolCachePolicy:
147     case WebCore::ReloadIgnoringCacheData:
148     case WebCore::RefreshAnyCacheData:
149         return false;
150     case WebCore::DoNotUseAnyCache:
151         ASSERT_NOT_REACHED();
152         return false;
153     }
154     return false;
155 }
156
157 static bool responseHasExpired(const WebCore::ResourceResponse& response, std::chrono::system_clock::time_point timestamp, std::optional<std::chrono::microseconds> maxStale)
158 {
159     if (response.cacheControlContainsNoCache())
160         return true;
161
162     auto age = WebCore::computeCurrentAge(response, timestamp);
163     auto lifetime = WebCore::computeFreshnessLifetimeForHTTPFamily(response, timestamp);
164
165     auto maximumStaleness = maxStale ? maxStale.value() : 0ms;
166     bool hasExpired = age - lifetime > maximumStaleness;
167
168 #ifndef LOG_DISABLED
169     if (hasExpired)
170         LOG(NetworkCache, "(NetworkProcess) needsRevalidation hasExpired age=%f lifetime=%f max-stale=%g", age, lifetime, maxStale);
171 #endif
172
173     return hasExpired;
174 }
175
176 static bool responseNeedsRevalidation(const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& request, std::chrono::system_clock::time_point timestamp)
177 {
178     auto requestDirectives = WebCore::parseCacheControlDirectives(request.httpHeaderFields());
179     if (requestDirectives.noCache)
180         return true;
181     // For requests we ignore max-age values other than zero.
182     if (requestDirectives.maxAge && requestDirectives.maxAge.value() == 0ms)
183         return true;
184
185     return responseHasExpired(response, timestamp, requestDirectives.maxStale);
186 }
187
188 static UseDecision makeUseDecision(const Entry& entry, const WebCore::ResourceRequest& request)
189 {
190     // The request is conditional so we force revalidation from the network. We merely check the disk cache
191     // so we can update the cache entry.
192     if (request.isConditional() && !entry.redirectRequest())
193         return UseDecision::Validate;
194
195     if (!WebCore::verifyVaryingRequestHeaders(entry.varyingRequestHeaders(), request))
196         return UseDecision::NoDueToVaryingHeaderMismatch;
197
198     // We never revalidate in the case of a history navigation.
199     if (cachePolicyAllowsExpired(request.cachePolicy()))
200         return UseDecision::Use;
201
202     if (!responseNeedsRevalidation(entry.response(), request, entry.timeStamp()))
203         return UseDecision::Use;
204
205     if (!entry.response().hasCacheValidatorFields())
206         return UseDecision::NoDueToMissingValidatorFields;
207
208     return entry.redirectRequest() ? UseDecision::NoDueToExpiredRedirect : UseDecision::Validate;
209 }
210
211 static RetrieveDecision makeRetrieveDecision(const WebCore::ResourceRequest& request)
212 {
213     ASSERT(request.cachePolicy() != WebCore::DoNotUseAnyCache);
214
215     // FIXME: Support HEAD requests.
216     if (request.httpMethod() != "GET")
217         return RetrieveDecision::NoDueToHTTPMethod;
218     if (request.cachePolicy() == WebCore::ReloadIgnoringCacheData && !request.isConditional())
219         return RetrieveDecision::NoDueToReloadIgnoringCache;
220
221     return RetrieveDecision::Yes;
222 }
223
224 static bool isMediaMIMEType(const String& type)
225 {
226     return startsWithLettersIgnoringASCIICase(type, "video/") || startsWithLettersIgnoringASCIICase(type, "audio/");
227 }
228
229 static std::optional<size_t> expectedTotalResourceSizeFromContentRange(const WebCore::ResourceResponse& response)
230 {
231     ASSERT(response.httpStatusCode() == 206);
232
233     auto contentRange = response.httpHeaderField(WebCore::HTTPHeaderName::ContentRange);
234     if (contentRange.isNull())
235         return { };
236
237     if (!contentRange.startsWith("bytes "))
238         return { };
239
240     auto slashPosition = contentRange.find('/');
241     if (slashPosition == notFound)
242         return { };
243
244     auto sizeStringLength = contentRange.length() - slashPosition - 1;
245     if (!sizeStringLength)
246         return { };
247
248     bool isValid;
249     auto size = StringView(contentRange).right(sizeStringLength).toIntStrict(isValid);
250     if (!isValid)
251         return { };
252
253     return size;
254 }
255
256 static StoreDecision makeStoreDecision(const WebCore::ResourceRequest& originalRequest, const WebCore::ResourceResponse& response, size_t bodySize)
257 {
258     if (!originalRequest.url().protocolIsInHTTPFamily() || !response.isHTTP())
259         return StoreDecision::NoDueToProtocol;
260
261     if (originalRequest.httpMethod() != "GET")
262         return StoreDecision::NoDueToHTTPMethod;
263
264     auto requestDirectives = WebCore::parseCacheControlDirectives(originalRequest.httpHeaderFields());
265     if (requestDirectives.noStore)
266         return StoreDecision::NoDueToNoStoreRequest;
267
268     if (response.cacheControlContainsNoStore())
269         return StoreDecision::NoDueToNoStoreResponse;
270
271     if (!WebCore::isStatusCodeCacheableByDefault(response.httpStatusCode())) {
272         // http://tools.ietf.org/html/rfc7234#section-4.3.2
273         bool hasExpirationHeaders = response.expires() || response.cacheControlMaxAge();
274         bool expirationHeadersAllowCaching = WebCore::isStatusCodePotentiallyCacheable(response.httpStatusCode()) && hasExpirationHeaders;
275         if (!expirationHeadersAllowCaching)
276             return StoreDecision::NoDueToHTTPStatusCode;
277     }
278
279     bool isMainResource = originalRequest.requester() == WebCore::ResourceRequest::Requester::Main;
280     bool storeUnconditionallyForHistoryNavigation = isMainResource || originalRequest.priority() == WebCore::ResourceLoadPriority::VeryHigh;
281     if (!storeUnconditionallyForHistoryNavigation) {
282         auto now = std::chrono::system_clock::now();
283         bool hasNonZeroLifetime = !response.cacheControlContainsNoCache() && WebCore::computeFreshnessLifetimeForHTTPFamily(response, now) > 0ms;
284
285         bool possiblyReusable = response.hasCacheValidatorFields() || hasNonZeroLifetime;
286         if (!possiblyReusable)
287             return StoreDecision::NoDueToUnlikelyToReuse;
288     }
289
290     // Streaming media fills the cache quickly and is unlikely to be reused.
291     // FIXME: We should introduce a separate media cache partition that doesn't affect other resources.
292     // FIXME: We should also make sure make the MSE paths are copy-free so we can use mapped buffers from disk effectively.
293     auto requester = originalRequest.requester();
294     bool isDefinitelyMedia = requester == WebCore::ResourceRequest::Requester::Media;
295     if (isDefinitelyMedia) {
296         // Allow caching of smaller media files if we know the total size.
297         const size_t maximumCacheableMediaSize = 5 * 1024 * 1024;
298         auto totalSize = response.httpStatusCode() == 206 ? expectedTotalResourceSizeFromContentRange(response) : bodySize;
299         if (!totalSize || *totalSize > maximumCacheableMediaSize)
300             return StoreDecision::NoDueToStreamingMedia;
301     }
302
303     bool isLikelyStreamingMedia = requester == WebCore::ResourceRequest::Requester::XHR && isMediaMIMEType(response.mimeType());
304     if (isLikelyStreamingMedia) {
305         // Media loaded via XHR is likely being used for MSE streaming (YouTube and Netflix for example).
306         // We have no way of knowing the total media size so disallow caching.
307         return StoreDecision::NoDueToStreamingMedia;
308     }
309
310     return StoreDecision::Yes;
311 }
312
313 void Cache::retrieve(const WebCore::ResourceRequest& request, const GlobalFrameID& frameID, Function<void (std::unique_ptr<Entry>)>&& completionHandler)
314 {
315     ASSERT(request.url().protocolIsInHTTPFamily());
316
317     LOG(NetworkCache, "(NetworkProcess) retrieving %s priority %d", request.url().string().ascii().data(), static_cast<int>(request.priority()));
318
319     if (m_statistics)
320         m_statistics->recordRetrievalRequest(frameID.first);
321
322     Key storageKey = makeCacheKey(request);
323
324 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
325     bool canUseSpeculativeRevalidation = m_speculativeLoadManager && !request.isConditional();
326     if (canUseSpeculativeRevalidation)
327         m_speculativeLoadManager->registerLoad(frameID, request, storageKey);
328 #endif
329
330     auto retrieveDecision = makeRetrieveDecision(request);
331     if (retrieveDecision != RetrieveDecision::Yes) {
332         if (m_statistics)
333             m_statistics->recordNotUsingCacheForRequest(frameID.first, storageKey, request, retrieveDecision);
334
335         completionHandler(nullptr);
336         return;
337     }
338
339 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
340     if (canUseSpeculativeRevalidation && m_speculativeLoadManager->canRetrieve(storageKey, request, frameID)) {
341         m_speculativeLoadManager->retrieve(storageKey, [request, completionHandler = WTFMove(completionHandler)](std::unique_ptr<Entry> entry) {
342             if (entry && WebCore::verifyVaryingRequestHeaders(entry->varyingRequestHeaders(), request))
343                 completionHandler(WTFMove(entry));
344             else
345                 completionHandler(nullptr);
346         });
347         return;
348     }
349 #endif
350
351     auto startTime = WallTime::now();
352     auto priority = static_cast<unsigned>(request.priority());
353
354     m_storage->retrieve(storageKey, priority, [this, protectedThis = makeRef(*this), request, completionHandler = WTFMove(completionHandler), startTime, storageKey, frameID](auto record) {
355         if (!record) {
356             LOG(NetworkCache, "(NetworkProcess) not found in storage");
357
358             if (m_statistics)
359                 m_statistics->recordRetrievalFailure(frameID.first, storageKey, request);
360
361             completionHandler(nullptr);
362             return false;
363         }
364
365         ASSERT(record->key == storageKey);
366
367         auto entry = Entry::decodeStorageRecord(*record);
368
369         auto useDecision = entry ? makeUseDecision(*entry, request) : UseDecision::NoDueToDecodeFailure;
370         switch (useDecision) {
371         case UseDecision::Use:
372             break;
373         case UseDecision::Validate:
374             entry->setNeedsValidation(true);
375             break;
376         default:
377             entry = nullptr;
378         };
379
380 #if !LOG_DISABLED
381         auto elapsed = WallTime::now() - startTime;
382         LOG(NetworkCache, "(NetworkProcess) retrieve complete useDecision=%d priority=%d time=%" PRIi64 "ms", static_cast<int>(useDecision), static_cast<int>(request.priority()), elapsed.millisecondsAs<int64_t>());
383 #else
384         UNUSED_PARAM(startTime);
385 #endif
386         completionHandler(WTFMove(entry));
387
388         if (m_statistics)
389             m_statistics->recordRetrievedCachedEntry(frameID.first, storageKey, request, useDecision);
390         return useDecision != UseDecision::NoDueToDecodeFailure;
391     });
392 }
393
394     
395 std::unique_ptr<Entry> Cache::makeEntry(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData)
396 {
397     return std::make_unique<Entry>(makeCacheKey(request), response, WTFMove(responseData), WebCore::collectVaryingRequestHeaders(request, response));
398 }
399
400 std::unique_ptr<Entry> Cache::makeRedirectEntry(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& redirectRequest)
401 {
402     return std::make_unique<Entry>(makeCacheKey(request), response, redirectRequest, WebCore::collectVaryingRequestHeaders(request, response));
403 }
404
405 std::unique_ptr<Entry> Cache::store(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData, Function<void (MappedBody&)>&& completionHandler)
406 {
407     ASSERT(responseData);
408
409     LOG(NetworkCache, "(NetworkProcess) storing %s, partition %s", request.url().string().latin1().data(), makeCacheKey(request).partition().latin1().data());
410
411     StoreDecision storeDecision = makeStoreDecision(request, response, responseData ? responseData->size() : 0);
412     if (storeDecision != StoreDecision::Yes) {
413         LOG(NetworkCache, "(NetworkProcess) didn't store, storeDecision=%d", static_cast<int>(storeDecision));
414         auto key = makeCacheKey(request);
415
416         auto isSuccessfulRevalidation = response.httpStatusCode() == 304;
417         if (!isSuccessfulRevalidation) {
418             // Make sure we don't keep a stale entry in the cache.
419             remove(key);
420         }
421
422         if (m_statistics)
423             m_statistics->recordNotCachingResponse(key, storeDecision);
424
425         return nullptr;
426     }
427
428     auto cacheEntry = makeEntry(request, response, WTFMove(responseData));
429     auto record = cacheEntry->encodeAsStorageRecord();
430
431     m_storage->store(record, [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)](const Data& bodyData) {
432         MappedBody mappedBody;
433 #if ENABLE(SHAREABLE_RESOURCE)
434         if (canUseSharedMemoryForBodyData()) {
435             if (auto sharedMemory = bodyData.tryCreateSharedMemory()) {
436                 mappedBody.shareableResource = ShareableResource::create(sharedMemory.releaseNonNull(), 0, bodyData.size());
437                 ASSERT(mappedBody.shareableResource);
438                 mappedBody.shareableResource->createHandle(mappedBody.shareableResourceHandle);
439             }
440         }
441 #endif
442         completionHandler(mappedBody);
443         LOG(NetworkCache, "(NetworkProcess) stored");
444     });
445
446     return cacheEntry;
447 }
448
449 std::unique_ptr<Entry> Cache::storeRedirect(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& redirectRequest)
450 {
451     LOG(NetworkCache, "(NetworkProcess) storing redirect %s -> %s", request.url().string().latin1().data(), redirectRequest.url().string().latin1().data());
452
453     StoreDecision storeDecision = makeStoreDecision(request, response, 0);
454     if (storeDecision != StoreDecision::Yes) {
455         LOG(NetworkCache, "(NetworkProcess) didn't store redirect, storeDecision=%d", static_cast<int>(storeDecision));
456         auto key = makeCacheKey(request);
457         if (m_statistics)
458             m_statistics->recordNotCachingResponse(key, storeDecision);
459
460         return nullptr;
461     }
462
463     auto cacheEntry = makeRedirectEntry(request, response, redirectRequest);
464     auto record = cacheEntry->encodeAsStorageRecord();
465
466     m_storage->store(record, nullptr);
467     
468     return cacheEntry;
469 }
470
471 std::unique_ptr<Entry> Cache::update(const WebCore::ResourceRequest& originalRequest, const GlobalFrameID& frameID, const Entry& existingEntry, const WebCore::ResourceResponse& validatingResponse)
472 {
473     LOG(NetworkCache, "(NetworkProcess) updating %s", originalRequest.url().string().latin1().data());
474
475     WebCore::ResourceResponse response = existingEntry.response();
476     WebCore::updateResponseHeadersAfterRevalidation(response, validatingResponse);
477
478     auto updateEntry = std::make_unique<Entry>(existingEntry.key(), response, existingEntry.buffer(), WebCore::collectVaryingRequestHeaders(originalRequest, response));
479     auto updateRecord = updateEntry->encodeAsStorageRecord();
480
481     m_storage->store(updateRecord, { });
482
483     if (m_statistics)
484         m_statistics->recordRevalidationSuccess(frameID.first, existingEntry.key(), originalRequest);
485
486     return updateEntry;
487 }
488
489 void Cache::remove(const Key& key)
490 {
491     m_storage->remove(key);
492 }
493
494 void Cache::remove(const WebCore::ResourceRequest& request)
495 {
496     remove(makeCacheKey(request));
497 }
498
499 void Cache::remove(const Vector<Key>& keys, Function<void ()>&& completionHandler)
500 {
501     m_storage->remove(keys, WTFMove(completionHandler));
502 }
503
504 void Cache::traverse(Function<void (const TraversalEntry*)>&& traverseHandler)
505 {
506     // Protect against clients making excessive traversal requests.
507     const unsigned maximumTraverseCount = 3;
508     if (m_traverseCount >= maximumTraverseCount) {
509         WTFLogAlways("Maximum parallel cache traverse count exceeded. Ignoring traversal request.");
510
511         RunLoop::main().dispatch([traverseHandler = WTFMove(traverseHandler)] {
512             traverseHandler(nullptr);
513         });
514         return;
515     }
516
517     ++m_traverseCount;
518
519     m_storage->traverse(resourceType(), 0, [this, protectedThis = makeRef(*this), traverseHandler = WTFMove(traverseHandler)](const Storage::Record* record, const Storage::RecordInfo& recordInfo) {
520         if (!record) {
521             --m_traverseCount;
522             traverseHandler(nullptr);
523             return;
524         }
525
526         auto entry = Entry::decodeStorageRecord(*record);
527         if (!entry)
528             return;
529
530         TraversalEntry traversalEntry { *entry, recordInfo };
531         traverseHandler(&traversalEntry);
532     });
533 }
534
535 String Cache::dumpFilePath() const
536 {
537     return pathByAppendingComponent(m_storage->versionPath(), "dump.json");
538 }
539
540 void Cache::dumpContentsToFile()
541 {
542     auto fd = openFile(dumpFilePath(), FileOpenMode::Write);
543     if (!isHandleValid(fd))
544         return;
545     auto prologue = String("{\n\"entries\": [\n").utf8();
546     writeToFile(fd, prologue.data(), prologue.length());
547
548     struct Totals {
549         unsigned count { 0 };
550         double worth { 0 };
551         size_t bodySize { 0 };
552     };
553     Totals totals;
554     auto flags = Storage::TraverseFlag::ComputeWorth | Storage::TraverseFlag::ShareCount;
555     size_t capacity = m_storage->capacity();
556     m_storage->traverse(resourceType(), flags, [fd, totals, capacity](const Storage::Record* record, const Storage::RecordInfo& info) mutable {
557         if (!record) {
558             StringBuilder epilogue;
559             epilogue.appendLiteral("{}\n],\n");
560             epilogue.appendLiteral("\"totals\": {\n");
561             epilogue.appendLiteral("\"capacity\": ");
562             epilogue.appendNumber(capacity);
563             epilogue.appendLiteral(",\n");
564             epilogue.appendLiteral("\"count\": ");
565             epilogue.appendNumber(totals.count);
566             epilogue.appendLiteral(",\n");
567             epilogue.appendLiteral("\"bodySize\": ");
568             epilogue.appendNumber(totals.bodySize);
569             epilogue.appendLiteral(",\n");
570             epilogue.appendLiteral("\"averageWorth\": ");
571             epilogue.appendNumber(totals.count ? totals.worth / totals.count : 0);
572             epilogue.appendLiteral("\n");
573             epilogue.appendLiteral("}\n}\n");
574             auto writeData = epilogue.toString().utf8();
575             writeToFile(fd, writeData.data(), writeData.length());
576             closeFile(fd);
577             return;
578         }
579         auto entry = Entry::decodeStorageRecord(*record);
580         if (!entry)
581             return;
582         ++totals.count;
583         totals.worth += info.worth;
584         totals.bodySize += info.bodySize;
585
586         StringBuilder json;
587         entry->asJSON(json, info);
588         json.appendLiteral(",\n");
589         auto writeData = json.toString().utf8();
590         writeToFile(fd, writeData.data(), writeData.length());
591     });
592 }
593
594 void Cache::deleteDumpFile()
595 {
596     WorkQueue::create("com.apple.WebKit.Cache.delete")->dispatch([path = dumpFilePath().isolatedCopy()] {
597         deleteFile(path);
598     });
599 }
600
601 void Cache::clear(std::chrono::system_clock::time_point modifiedSince, Function<void ()>&& completionHandler)
602 {
603     LOG(NetworkCache, "(NetworkProcess) clearing cache");
604
605     if (m_statistics)
606         m_statistics->clear();
607
608     String anyType;
609     m_storage->clear(anyType, modifiedSince, WTFMove(completionHandler));
610
611     deleteDumpFile();
612 }
613
614 void Cache::clear()
615 {
616     clear(std::chrono::system_clock::time_point::min(), nullptr);
617 }
618
619 String Cache::recordsPath() const
620 {
621     return m_storage->recordsPath();
622 }
623
624 void Cache::retrieveData(const DataKey& dataKey, Function<void (const uint8_t* data, size_t size)> completionHandler)
625 {
626     Key key { dataKey, m_storage->salt() };
627     m_storage->retrieve(key, 4, [completionHandler = WTFMove(completionHandler)] (auto record) {
628         if (!record || !record->body.size()) {
629             completionHandler(nullptr, 0);
630             return true;
631         }
632         completionHandler(record->body.data(), record->body.size());
633         return true;
634     });
635 }
636
637 void Cache::storeData(const DataKey& dataKey, const uint8_t* data, size_t size)
638 {
639     Key key { dataKey, m_storage->salt() };
640     Storage::Record record { key, std::chrono::system_clock::now(), { }, Data { data, size }, { } };
641     m_storage->store(record, { });
642 }
643
644 }
645 }