Do not add a caches to its engine if the salt cannot be initialized
[WebKit-https.git] / Source / WebKit / NetworkProcess / cache / CacheStorageEngine.cpp
1 /*
2  * Copyright (C) 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. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "CacheStorageEngine.h"
28
29 #include "Logging.h"
30 #include "NetworkCacheFileSystem.h"
31 #include "NetworkCacheIOChannel.h"
32 #include "NetworkProcess.h"
33 #include "WebsiteDataType.h"
34 #include <WebCore/CacheQueryOptions.h>
35 #include <WebCore/SecurityOrigin.h>
36 #include <pal/SessionID.h>
37 #include <wtf/CallbackAggregator.h>
38 #include <wtf/NeverDestroyed.h>
39 #include <wtf/text/StringBuilder.h>
40 #include <wtf/text/StringHash.h>
41
42 namespace WebKit {
43
44 namespace CacheStorage {
45
46 using namespace WebCore::DOMCacheEngine;
47 using namespace NetworkCache;
48
49 String Engine::cachesRootPath(const WebCore::ClientOrigin& origin)
50 {
51     if (!shouldPersist() || !m_salt)
52         return { };
53
54     Key key(origin.topOrigin.toString(), origin.clientOrigin.toString(), { }, { }, salt());
55     return FileSystem::pathByAppendingComponent(rootPath(), key.hashAsString());
56 }
57
58 Engine::~Engine()
59 {
60     for (auto& caches : m_caches.values())
61         caches->detach();
62
63     auto initializationCallbacks = WTFMove(m_initializationCallbacks);
64     for (auto& callback : initializationCallbacks)
65         callback(Error::Internal);
66
67     auto writeCallbacks = WTFMove(m_pendingWriteCallbacks);
68     for (auto& callback : writeCallbacks.values())
69         callback(Error::Internal);
70
71     auto readCallbacks = WTFMove(m_pendingReadCallbacks);
72     for (auto& callback : readCallbacks.values())
73         callback(Data { }, 1);
74 }
75
76 void Engine::from(NetworkProcess& networkProcess, PAL::SessionID sessionID, Function<void(Engine&)>&& callback)
77 {
78     if (auto* engine = networkProcess.findCacheEngine(sessionID)) {
79         callback(*engine);
80         return;
81     }
82
83     networkProcess.cacheStorageParameters(sessionID, [networkProcess = makeRef(networkProcess), sessionID, callback = WTFMove(callback)] (auto&& rootPath, auto quota) mutable {
84         callback(networkProcess->ensureCacheEngine(sessionID, [&] {
85             return adoptRef(*new Engine { sessionID, networkProcess.get(), String { rootPath }, quota });
86         }));
87     });
88 }
89
90 void Engine::destroyEngine(NetworkProcess& networkProcess, PAL::SessionID sessionID)
91 {
92     ASSERT(sessionID != PAL::SessionID::defaultSessionID());
93     networkProcess.removeCacheEngine(sessionID);
94 }
95
96 void Engine::fetchEntries(NetworkProcess& networkProcess, PAL::SessionID sessionID, bool shouldComputeSize, CompletionHandler<void(Vector<WebsiteData::Entry>)>&& completionHandler)
97 {
98     from(networkProcess, sessionID, [shouldComputeSize, completionHandler = WTFMove(completionHandler)] (auto& engine) mutable {
99         engine.fetchEntries(shouldComputeSize, WTFMove(completionHandler));
100     });
101 }
102
103 void Engine::open(NetworkProcess& networkProcess, PAL::SessionID sessionID, WebCore::ClientOrigin&& origin, String&& cacheName, WebCore::DOMCacheEngine::CacheIdentifierCallback&& callback)
104 {
105     from(networkProcess, sessionID, [origin = WTFMove(origin), cacheName = WTFMove(cacheName), callback = WTFMove(callback)](auto& engine) mutable {
106         engine.open(origin, cacheName, WTFMove(callback));
107     });
108 }
109
110 void Engine::remove(NetworkProcess& networkProcess, PAL::SessionID sessionID, uint64_t cacheIdentifier, WebCore::DOMCacheEngine::CacheIdentifierCallback&& callback)
111 {
112     from(networkProcess, sessionID, [cacheIdentifier, callback = WTFMove(callback)](auto& engine) mutable {
113         engine.remove(cacheIdentifier, WTFMove(callback));
114     });
115 }
116
117 void Engine::retrieveCaches(NetworkProcess& networkProcess, PAL::SessionID sessionID, WebCore::ClientOrigin&& origin, uint64_t updateCounter, WebCore::DOMCacheEngine::CacheInfosCallback&& callback)
118 {
119     from(networkProcess, sessionID, [origin = WTFMove(origin), updateCounter, callback = WTFMove(callback)](auto& engine) mutable {
120         engine.retrieveCaches(origin, updateCounter, WTFMove(callback));
121     });
122 }
123
124
125 void Engine::retrieveRecords(NetworkProcess& networkProcess, PAL::SessionID sessionID, uint64_t cacheIdentifier, URL&& url, WebCore::DOMCacheEngine::RecordsCallback&& callback)
126 {
127     from(networkProcess, sessionID, [cacheIdentifier, url = WTFMove(url), callback = WTFMove(callback)](auto& engine) mutable {
128         engine.retrieveRecords(cacheIdentifier, WTFMove(url), WTFMove(callback));
129     });
130 }
131
132 void Engine::putRecords(NetworkProcess& networkProcess, PAL::SessionID sessionID, uint64_t cacheIdentifier, Vector<WebCore::DOMCacheEngine::Record>&& records, WebCore::DOMCacheEngine::RecordIdentifiersCallback&& callback)
133 {
134     from(networkProcess, sessionID, [cacheIdentifier, records = WTFMove(records), callback = WTFMove(callback)](auto& engine) mutable {
135         engine.putRecords(cacheIdentifier, WTFMove(records), WTFMove(callback));
136     });
137 }
138
139 void Engine::deleteMatchingRecords(NetworkProcess& networkProcess, PAL::SessionID sessionID, uint64_t cacheIdentifier, WebCore::ResourceRequest&& request, WebCore::CacheQueryOptions&& options, WebCore::DOMCacheEngine::RecordIdentifiersCallback&& callback)
140 {
141     from(networkProcess, sessionID, [cacheIdentifier, request = WTFMove(request), options = WTFMove(options), callback = WTFMove(callback)](auto& engine) mutable {
142         engine.deleteMatchingRecords(cacheIdentifier, WTFMove(request), WTFMove(options), WTFMove(callback));
143     });
144 }
145
146 void Engine::lock(NetworkProcess& networkProcess, PAL::SessionID sessionID, uint64_t cacheIdentifier)
147 {
148     from(networkProcess, sessionID, [cacheIdentifier](auto& engine) mutable {
149         engine.lock(cacheIdentifier);
150     });
151 }
152
153 void Engine::unlock(NetworkProcess& networkProcess, PAL::SessionID sessionID, uint64_t cacheIdentifier)
154 {
155     from(networkProcess, sessionID, [cacheIdentifier](auto& engine) mutable {
156         engine.unlock(cacheIdentifier);
157     });
158 }
159
160 void Engine::clearMemoryRepresentation(NetworkProcess& networkProcess, PAL::SessionID sessionID, WebCore::ClientOrigin&& origin, WebCore::DOMCacheEngine::CompletionCallback&& callback)
161 {
162     from(networkProcess, sessionID, [origin = WTFMove(origin), callback = WTFMove(callback)](auto& engine) mutable {
163         engine.clearMemoryRepresentation(origin, WTFMove(callback));
164     });
165 }
166
167 void Engine::representation(NetworkProcess& networkProcess, PAL::SessionID sessionID, CompletionHandler<void(String&&)>&& callback)
168 {
169     from(networkProcess, sessionID, [callback = WTFMove(callback)](auto& engine) mutable {
170         callback(engine.representation());
171     });
172 }
173
174 void Engine::clearAllCaches(NetworkProcess& networkProcess, PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
175 {
176     from(networkProcess, sessionID, [completionHandler = WTFMove(completionHandler)](auto& engine) mutable {
177         engine.clearAllCaches(WTFMove(completionHandler));
178     });
179 }
180
181 void Engine::clearCachesForOrigin(NetworkProcess& networkProcess, PAL::SessionID sessionID, WebCore::SecurityOriginData&& originData, CompletionHandler<void()>&& completionHandler)
182 {
183     from(networkProcess, sessionID, [originData = WTFMove(originData), completionHandler = WTFMove(completionHandler)](auto& engine) mutable {
184         engine.clearCachesForOrigin(originData, WTFMove(completionHandler));
185     });
186 }
187
188 Engine::Engine(PAL::SessionID sessionID, NetworkProcess& process, String&& rootPath, uint64_t quota)
189     : m_sessionID(sessionID)
190     , m_networkProcess(makeWeakPtr(process))
191     , m_rootPath(WTFMove(rootPath))
192     , m_quota(quota)
193 {
194     if (!m_rootPath.isNull())
195         m_ioQueue = WorkQueue::create("com.apple.WebKit.CacheStorageEngine.serialBackground", WorkQueue::Type::Serial, WorkQueue::QOS::Background);
196 }
197
198 void Engine::open(const WebCore::ClientOrigin& origin, const String& cacheName, CacheIdentifierCallback&& callback)
199 {
200     readCachesFromDisk(origin, [cacheName, callback = WTFMove(callback)](CachesOrError&& cachesOrError) mutable {
201         if (!cachesOrError.has_value()) {
202             callback(makeUnexpected(cachesOrError.error()));
203             return;
204         }
205
206         cachesOrError.value().get().open(cacheName, WTFMove(callback));
207     });
208 }
209
210 void Engine::remove(uint64_t cacheIdentifier, CacheIdentifierCallback&& callback)
211 {
212     Caches* cachesToModify = nullptr;
213     for (auto& caches : m_caches.values()) {
214         auto* cacheToRemove = caches->find(cacheIdentifier);
215         if (cacheToRemove) {
216             cachesToModify = caches.get();
217             break;
218         }
219     }
220     if (!cachesToModify) {
221         callback(makeUnexpected(Error::Internal));
222         return;
223     }
224
225     cachesToModify->remove(cacheIdentifier, WTFMove(callback));
226 }
227
228 void Engine::retrieveCaches(const WebCore::ClientOrigin& origin, uint64_t updateCounter, CacheInfosCallback&& callback)
229 {
230     readCachesFromDisk(origin, [updateCounter, callback = WTFMove(callback)](CachesOrError&& cachesOrError) mutable {
231         if (!cachesOrError.has_value()) {
232             callback(makeUnexpected(cachesOrError.error()));
233             return;
234         }
235
236         cachesOrError.value().get().cacheInfos(updateCounter, WTFMove(callback));
237     });
238 }
239
240 void Engine::retrieveRecords(uint64_t cacheIdentifier, URL&& url, RecordsCallback&& callback)
241 {
242     readCache(cacheIdentifier, [url = WTFMove(url), callback = WTFMove(callback)](CacheOrError&& result) mutable {
243         if (!result.has_value()) {
244             callback(makeUnexpected(result.error()));
245             return;
246         }
247         result.value().get().retrieveRecords(url, WTFMove(callback));
248     });
249 }
250
251 void Engine::putRecords(uint64_t cacheIdentifier, Vector<Record>&& records, RecordIdentifiersCallback&& callback)
252 {
253     readCache(cacheIdentifier, [records = WTFMove(records), callback = WTFMove(callback)](CacheOrError&& result) mutable {
254         if (!result.has_value()) {
255             callback(makeUnexpected(result.error()));
256             return;
257         }
258
259         result.value().get().put(WTFMove(records), WTFMove(callback));
260     });
261 }
262
263 void Engine::deleteMatchingRecords(uint64_t cacheIdentifier, WebCore::ResourceRequest&& request, WebCore::CacheQueryOptions&& options, RecordIdentifiersCallback&& callback)
264 {
265     readCache(cacheIdentifier, [request = WTFMove(request), options = WTFMove(options), callback = WTFMove(callback)](CacheOrError&& result) mutable {
266         if (!result.has_value()) {
267             callback(makeUnexpected(result.error()));
268             return;
269         }
270
271         result.value().get().remove(WTFMove(request), WTFMove(options), WTFMove(callback));
272     });
273 }
274
275 void Engine::initialize(CompletionCallback&& callback)
276 {
277     if (m_salt) {
278         callback(WTF::nullopt);
279         return;
280     }
281
282     if (!shouldPersist()) {
283         m_salt = NetworkCache::Salt { };
284         callback(WTF::nullopt);
285         return;
286     }
287
288     bool shouldComputeSalt = m_initializationCallbacks.isEmpty();
289     m_initializationCallbacks.append(WTFMove(callback));
290
291     if (!shouldComputeSalt)
292         return;
293
294     String saltPath = FileSystem::pathByAppendingComponent(m_rootPath, "salt"_s);
295     m_ioQueue->dispatch([this, weakThis = makeWeakPtr(this), saltPath = WTFMove(saltPath)] () mutable {
296         FileSystem::makeAllDirectories(m_rootPath);
297         RunLoop::main().dispatch([this, weakThis = WTFMove(weakThis), salt = readOrMakeSalt(saltPath)]() mutable {
298             if (!weakThis)
299                 return;
300
301             m_salt = WTFMove(salt);
302
303             auto callbacks = WTFMove(m_initializationCallbacks);
304             for (auto& callback : callbacks)
305                 callback(m_salt ? WTF::nullopt : makeOptional(Error::WriteDisk));
306         });
307     });
308 }
309
310 void Engine::readCachesFromDisk(const WebCore::ClientOrigin& origin, CachesCallback&& callback)
311 {
312     initialize([this, origin, callback = WTFMove(callback)](Optional<Error>&& error) mutable {
313         if (error) {
314             callback(makeUnexpected(error.value()));
315             return;
316         }
317
318         auto& caches = m_caches.ensure(origin, [&origin, this] {
319             auto path = cachesRootPath(origin);
320             return Caches::create(*this, WebCore::ClientOrigin { origin }, WTFMove(path), m_quota);
321         }).iterator->value;
322
323         if (caches->isInitialized()) {
324             callback(std::reference_wrapper<Caches> { *caches });
325             return;
326         }
327
328         caches->initialize([callback = WTFMove(callback), caches = caches.copyRef()](Optional<Error>&& error) mutable {
329             if (error) {
330                 callback(makeUnexpected(error.value()));
331                 return;
332             }
333
334             callback(std::reference_wrapper<Caches> { *caches });
335         });
336     });
337 }
338
339 void Engine::readCache(uint64_t cacheIdentifier, CacheCallback&& callback)
340 {
341     auto* cache = this->cache(cacheIdentifier);
342     if (!cache) {
343         callback(makeUnexpected(Error::Internal));
344         return;
345     }
346     if (!cache->isOpened()) {
347         cache->open([this, protectedThis = makeRef(*this), cacheIdentifier, callback = WTFMove(callback)](Optional<Error>&& error) mutable {
348             if (error) {
349                 callback(makeUnexpected(error.value()));
350                 return;
351             }
352
353             auto* cache = this->cache(cacheIdentifier);
354             if (!cache) {
355                 callback(makeUnexpected(Error::Internal));
356                 return;
357             }
358             ASSERT(cache->isOpened());
359             callback(std::reference_wrapper<Cache> { *cache });
360         });
361         return;
362     }
363     callback(std::reference_wrapper<Cache> { *cache });
364 }
365
366 Cache* Engine::cache(uint64_t cacheIdentifier)
367 {
368     Cache* result = nullptr;
369     for (auto& caches : m_caches.values()) {
370         if ((result = caches->find(cacheIdentifier)))
371             break;
372     }
373     return result;
374 }
375
376 void Engine::writeFile(const String& filename, NetworkCache::Data&& data, WebCore::DOMCacheEngine::CompletionCallback&& callback)
377 {
378     if (!shouldPersist()) {
379         callback(WTF::nullopt);
380         return;
381     }
382
383     m_pendingWriteCallbacks.add(++m_pendingCallbacksCounter, WTFMove(callback));
384     m_ioQueue->dispatch([this, weakThis = makeWeakPtr(this), identifier = m_pendingCallbacksCounter, data = WTFMove(data), filename = filename.isolatedCopy()]() mutable {
385
386         String directoryPath = FileSystem::directoryName(filename);
387         if (!FileSystem::fileExists(directoryPath))
388             FileSystem::makeAllDirectories(directoryPath);
389
390         auto channel = IOChannel::open(filename, IOChannel::Type::Create);
391         channel->write(0, data, nullptr, [this, weakThis = WTFMove(weakThis), identifier](int error) mutable {
392             ASSERT(RunLoop::isMain());
393             if (!weakThis)
394                 return;
395
396             auto callback = m_pendingWriteCallbacks.take(identifier);
397             if (error) {
398                 RELEASE_LOG_ERROR(CacheStorage, "CacheStorage::Engine::writeFile failed with error %d", error);
399
400                 callback(Error::WriteDisk);
401                 return;
402             }
403             callback(WTF::nullopt);
404         });
405     });
406 }
407
408 void Engine::readFile(const String& filename, CompletionHandler<void(const NetworkCache::Data&, int error)>&& callback)
409 {
410     if (!shouldPersist()) {
411         callback(Data { }, 0);
412         return;
413     }
414
415     m_pendingReadCallbacks.add(++m_pendingCallbacksCounter, WTFMove(callback));
416     m_ioQueue->dispatch([this, weakThis = makeWeakPtr(this), identifier = m_pendingCallbacksCounter, filename = filename.isolatedCopy()]() mutable {
417         auto channel = IOChannel::open(filename, IOChannel::Type::Read);
418         if (channel->fileDescriptor() < 0) {
419             RunLoop::main().dispatch([this, weakThis = WTFMove(weakThis), identifier]() mutable {
420                 if (!weakThis)
421                     return;
422
423                 m_pendingReadCallbacks.take(identifier)(Data { }, 0);
424             });
425             return;
426         }
427
428         channel->read(0, std::numeric_limits<size_t>::max(), nullptr, [this, weakThis = WTFMove(weakThis), identifier](const Data& data, int error) mutable {
429             RELEASE_LOG_ERROR_IF(error, CacheStorage, "CacheStorage::Engine::readFile failed with error %d", error);
430
431             // FIXME: We should do the decoding in the background thread.
432             ASSERT(RunLoop::isMain());
433
434             if (!weakThis)
435                 return;
436
437             m_pendingReadCallbacks.take(identifier)(data, error);
438         });
439     });
440 }
441
442 void Engine::removeFile(const String& filename)
443 {
444     if (!shouldPersist())
445         return;
446
447     m_ioQueue->dispatch([filename = filename.isolatedCopy()]() mutable {
448         FileSystem::deleteFile(filename);
449     });
450 }
451
452 class ReadOriginsTaskCounter : public RefCounted<ReadOriginsTaskCounter> {
453 public:
454     static Ref<ReadOriginsTaskCounter> create(WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)>&& callback)
455     {
456         return adoptRef(*new ReadOriginsTaskCounter(WTFMove(callback)));
457     }
458
459     ~ReadOriginsTaskCounter()
460     {
461         m_callback(WTFMove(m_entries));
462     }
463
464     void addOrigin(WebCore::SecurityOriginData&& origin, uint64_t size)
465     {
466         m_entries.append(WebsiteData::Entry { WTFMove(origin), WebsiteDataType::DOMCache, size });
467     }
468
469 private:
470     explicit ReadOriginsTaskCounter(WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)>&& callback)
471         : m_callback(WTFMove(callback))
472     {
473     }
474
475     WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)> m_callback;
476     Vector<WebsiteData::Entry> m_entries;
477 };
478
479 void Engine::fetchEntries(bool shouldComputeSize, WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)>&& completionHandler)
480 {
481     if (!shouldPersist()) {
482         auto entries = WTF::map(m_caches, [] (auto& pair) {
483             return WebsiteData::Entry { pair.value->origin().clientOrigin, WebsiteDataType::DOMCache, 0 };
484         });
485         completionHandler(WTFMove(entries));
486         return;
487     }
488
489     auto taskCounter = ReadOriginsTaskCounter::create(WTFMove(completionHandler));
490     for (auto& folderPath : FileSystem::listDirectory(m_rootPath, "*")) {
491         if (!FileSystem::fileIsDirectory(folderPath, FileSystem::ShouldFollowSymbolicLinks::No))
492             continue;
493         Caches::retrieveOriginFromDirectory(folderPath, *m_ioQueue, [protectedThis = makeRef(*this), shouldComputeSize, taskCounter = taskCounter.copyRef()] (auto&& origin) mutable {
494             ASSERT(RunLoop::isMain());
495             if (!origin)
496                 return;
497
498             if (!shouldComputeSize) {
499                 taskCounter->addOrigin(WTFMove(origin->topOrigin), 0);
500                 taskCounter->addOrigin(WTFMove(origin->clientOrigin), 0);
501                 return;
502             }
503
504             protectedThis->readCachesFromDisk(origin.value(), [origin = origin.value(), taskCounter = WTFMove(taskCounter)] (CachesOrError&& result) mutable {
505                 if (!result.has_value())
506                     return;
507                 taskCounter->addOrigin(WTFMove(origin.topOrigin), 0);
508                 taskCounter->addOrigin(WTFMove(origin.clientOrigin), result.value().get().storageSize());
509             });
510         });
511     }
512 }
513
514 void Engine::clearAllCaches(CompletionHandler<void()>&& completionHandler)
515 {
516     ASSERT(RunLoop::isMain());
517
518     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
519
520     for (auto& caches : m_caches.values())
521         caches->clear([callbackAggregator = callbackAggregator.copyRef()] { });
522
523     if (!shouldPersist())
524         return;
525
526     clearAllCachesFromDisk([callbackAggregator = WTFMove(callbackAggregator)] { });
527 }
528
529 void Engine::clearAllCachesFromDisk(CompletionHandler<void()>&& completionHandler)
530 {
531     ASSERT(RunLoop::isMain());
532
533     m_ioQueue->dispatch([path = m_rootPath.isolatedCopy(), completionHandler = WTFMove(completionHandler)]() mutable {
534         for (auto& filename : FileSystem::listDirectory(path, "*")) {
535             if (FileSystem::fileIsDirectory(filename, FileSystem::ShouldFollowSymbolicLinks::No))
536                 deleteDirectoryRecursively(filename);
537         }
538         RunLoop::main().dispatch(WTFMove(completionHandler));
539     });
540 }
541
542 void Engine::clearCachesForOrigin(const WebCore::SecurityOriginData& origin, CompletionHandler<void()>&& completionHandler)
543 {
544     ASSERT(RunLoop::isMain());
545
546     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
547
548     for (auto& keyValue : m_caches) {
549         if (keyValue.key.topOrigin == origin || keyValue.key.clientOrigin == origin)
550             keyValue.value->clear([callbackAggregator = callbackAggregator.copyRef()] { });
551     }
552
553     if (!shouldPersist())
554         return;
555
556     clearCachesForOriginFromDisk(origin, [callbackAggregator = WTFMove(callbackAggregator)] { });
557 }
558
559 void Engine::clearCachesForOriginFromDisk(const WebCore::SecurityOriginData& origin, CompletionHandler<void()>&& completionHandler)
560 {
561     ASSERT(RunLoop::isMain());
562
563     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
564
565     for (auto& folderPath : FileSystem::listDirectory(m_rootPath, "*")) {
566         if (!FileSystem::fileIsDirectory(folderPath, FileSystem::ShouldFollowSymbolicLinks::No))
567             continue;
568         Caches::retrieveOriginFromDirectory(folderPath, *m_ioQueue, [this, protectedThis = makeRef(*this), origin, callbackAggregator = callbackAggregator.copyRef(), folderPath] (Optional<WebCore::ClientOrigin>&& folderOrigin) mutable {
569             if (!folderOrigin)
570                 return;
571             if (folderOrigin->topOrigin != origin && folderOrigin->clientOrigin != origin)
572                 return;
573
574             ASSERT(folderPath == cachesRootPath(*folderOrigin));
575             deleteDirectoryRecursivelyOnBackgroundThread(folderPath, [callbackAggregator = WTFMove(callbackAggregator)] { });
576         });
577     }
578 }
579
580 void Engine::deleteDirectoryRecursivelyOnBackgroundThread(const String& path, CompletionHandler<void()>&& completionHandler)
581 {
582     ASSERT(RunLoop::isMain());
583
584     m_ioQueue->dispatch([path = path.isolatedCopy(), completionHandler = WTFMove(completionHandler)]() mutable {
585         deleteDirectoryRecursively(path);
586
587         RunLoop::main().dispatch(WTFMove(completionHandler));
588     });
589 }
590
591 void Engine::clearMemoryRepresentation(const WebCore::ClientOrigin& origin, WebCore::DOMCacheEngine::CompletionCallback&& callback)
592 {
593     readCachesFromDisk(origin, [callback = WTFMove(callback)](CachesOrError&& result) {
594         if (!result.has_value()) {
595             callback(result.error());
596             return;
597         }
598         result.value().get().clearMemoryRepresentation();
599         callback(WTF::nullopt);
600     });
601 }
602
603 void Engine::lock(uint64_t cacheIdentifier)
604 {
605     auto& counter = m_cacheLocks.ensure(cacheIdentifier, []() {
606         return 0;
607     }).iterator->value;
608
609     ++counter;
610 }
611
612 void Engine::unlock(uint64_t cacheIdentifier)
613 {
614     auto lockCount = m_cacheLocks.find(cacheIdentifier);
615     if (lockCount == m_cacheLocks.end())
616         return;
617
618     ASSERT(lockCount->value);
619     if (--lockCount->value)
620         return;
621
622     auto* cache = this->cache(cacheIdentifier);
623     if (!cache)
624         return;
625
626     cache->dispose();
627 }
628
629 String Engine::representation()
630 {
631     bool isFirst = true;
632     StringBuilder builder;
633     builder.append("{ \"path\": \"");
634     builder.append(m_rootPath);
635     builder.append("\", \"origins\": [");
636     for (auto& keyValue : m_caches) {
637         if (!isFirst)
638             builder.append(",");
639         isFirst = false;
640
641         builder.append("\n{ \"origin\" : { \"topOrigin\" : \"");
642         builder.append(keyValue.key.topOrigin.toString());
643         builder.append("\", \"clientOrigin\": \"");
644         builder.append(keyValue.key.clientOrigin.toString());
645         builder.append("\" }, \"caches\" : ");
646         keyValue.value->appendRepresentation(builder);
647         builder.append("}");
648     }
649     builder.append("]}");
650     return builder.toString();
651 }
652
653 void Engine::requestSpace(const WebCore::ClientOrigin& origin, uint64_t quota, uint64_t currentSize, uint64_t spaceRequired, RequestSpaceCallback&& callback)
654 {
655     if (!m_networkProcess) {
656         callback({ });
657         return;
658     }
659     m_networkProcess->requestCacheStorageSpace(m_sessionID, origin, quota, currentSize, spaceRequired, WTFMove(callback));
660 }
661
662 } // namespace CacheStorage
663
664 } // namespace WebKit