e390b5e7848c0806f924685c5635c005f7b2390c
[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.cacheStorageRootPath(sessionID, [networkProcess = makeRef(networkProcess), sessionID, callback = WTFMove(callback)] (auto&& rootPath) mutable {
84         callback(networkProcess->ensureCacheEngine(sessionID, [&] {
85             return adoptRef(*new Engine { sessionID, networkProcess.get(), WTFMove(rootPath) });
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)
189     : m_sessionID(sessionID)
190     , m_networkProcess(makeWeakPtr(process))
191     , m_rootPath(WTFMove(rootPath))
192 {
193     if (!m_rootPath.isNull())
194         m_ioQueue = WorkQueue::create("com.apple.WebKit.CacheStorageEngine.serialBackground", WorkQueue::Type::Serial, WorkQueue::QOS::Background);
195 }
196
197 void Engine::open(const WebCore::ClientOrigin& origin, const String& cacheName, CacheIdentifierCallback&& callback)
198 {
199     readCachesFromDisk(origin, [cacheName, callback = WTFMove(callback)](CachesOrError&& cachesOrError) mutable {
200         if (!cachesOrError.has_value()) {
201             callback(makeUnexpected(cachesOrError.error()));
202             return;
203         }
204
205         cachesOrError.value().get().open(cacheName, WTFMove(callback));
206     });
207 }
208
209 void Engine::remove(uint64_t cacheIdentifier, CacheIdentifierCallback&& callback)
210 {
211     Caches* cachesToModify = nullptr;
212     for (auto& caches : m_caches.values()) {
213         auto* cacheToRemove = caches->find(cacheIdentifier);
214         if (cacheToRemove) {
215             cachesToModify = caches.get();
216             break;
217         }
218     }
219     if (!cachesToModify) {
220         callback(makeUnexpected(Error::Internal));
221         return;
222     }
223
224     cachesToModify->remove(cacheIdentifier, WTFMove(callback));
225 }
226
227 void Engine::retrieveCaches(const WebCore::ClientOrigin& origin, uint64_t updateCounter, CacheInfosCallback&& callback)
228 {
229     readCachesFromDisk(origin, [updateCounter, callback = WTFMove(callback)](CachesOrError&& cachesOrError) mutable {
230         if (!cachesOrError.has_value()) {
231             callback(makeUnexpected(cachesOrError.error()));
232             return;
233         }
234
235         cachesOrError.value().get().cacheInfos(updateCounter, WTFMove(callback));
236     });
237 }
238
239 void Engine::retrieveRecords(uint64_t cacheIdentifier, URL&& url, RecordsCallback&& callback)
240 {
241     readCache(cacheIdentifier, [url = WTFMove(url), callback = WTFMove(callback)](CacheOrError&& result) mutable {
242         if (!result.has_value()) {
243             callback(makeUnexpected(result.error()));
244             return;
245         }
246         result.value().get().retrieveRecords(url, WTFMove(callback));
247     });
248 }
249
250 void Engine::putRecords(uint64_t cacheIdentifier, Vector<Record>&& records, RecordIdentifiersCallback&& callback)
251 {
252     readCache(cacheIdentifier, [records = WTFMove(records), callback = WTFMove(callback)](CacheOrError&& result) mutable {
253         if (!result.has_value()) {
254             callback(makeUnexpected(result.error()));
255             return;
256         }
257
258         result.value().get().put(WTFMove(records), WTFMove(callback));
259     });
260 }
261
262 void Engine::deleteMatchingRecords(uint64_t cacheIdentifier, WebCore::ResourceRequest&& request, WebCore::CacheQueryOptions&& options, RecordIdentifiersCallback&& callback)
263 {
264     readCache(cacheIdentifier, [request = WTFMove(request), options = WTFMove(options), callback = WTFMove(callback)](CacheOrError&& result) mutable {
265         if (!result.has_value()) {
266             callback(makeUnexpected(result.error()));
267             return;
268         }
269
270         result.value().get().remove(WTFMove(request), WTFMove(options), WTFMove(callback));
271     });
272 }
273
274 void Engine::initialize(CompletionCallback&& callback)
275 {
276     if (m_salt) {
277         callback(WTF::nullopt);
278         return;
279     }
280
281     if (!shouldPersist()) {
282         m_salt = NetworkCache::Salt { };
283         callback(WTF::nullopt);
284         return;
285     }
286
287     bool shouldComputeSalt = m_initializationCallbacks.isEmpty();
288     m_initializationCallbacks.append(WTFMove(callback));
289
290     if (!shouldComputeSalt)
291         return;
292
293     String saltPath = FileSystem::pathByAppendingComponent(m_rootPath, "salt"_s);
294     m_ioQueue->dispatch([this, weakThis = makeWeakPtr(this), saltPath = WTFMove(saltPath)] () mutable {
295         FileSystem::makeAllDirectories(m_rootPath);
296         RunLoop::main().dispatch([this, weakThis = WTFMove(weakThis), salt = readOrMakeSalt(saltPath)]() mutable {
297             if (!weakThis)
298                 return;
299
300             m_salt = WTFMove(salt);
301
302             auto callbacks = WTFMove(m_initializationCallbacks);
303             for (auto& callback : callbacks)
304                 callback(m_salt ? WTF::nullopt : makeOptional(Error::WriteDisk));
305         });
306     });
307 }
308
309 void Engine::readCachesFromDisk(const WebCore::ClientOrigin& origin, CachesCallback&& callback)
310 {
311     initialize([this, origin, callback = WTFMove(callback)](Optional<Error>&& error) mutable {
312         if (error) {
313             callback(makeUnexpected(error.value()));
314             return;
315         }
316
317         auto& caches = m_caches.ensure(origin, [&origin, this] {
318             auto path = cachesRootPath(origin);
319             return Caches::create(*this, WebCore::ClientOrigin { origin }, WTFMove(path), m_networkProcess->storageQuotaManager(m_sessionID, origin));
320         }).iterator->value;
321
322         if (caches->isInitialized()) {
323             callback(std::reference_wrapper<Caches> { *caches });
324             return;
325         }
326
327         caches->initialize([callback = WTFMove(callback), caches = caches.copyRef()](Optional<Error>&& error) mutable {
328             if (error) {
329                 callback(makeUnexpected(error.value()));
330                 return;
331             }
332
333             callback(std::reference_wrapper<Caches> { *caches });
334         });
335     });
336 }
337
338 void Engine::readCache(uint64_t cacheIdentifier, CacheCallback&& callback)
339 {
340     auto* cache = this->cache(cacheIdentifier);
341     if (!cache) {
342         callback(makeUnexpected(Error::Internal));
343         return;
344     }
345     if (!cache->isOpened()) {
346         cache->open([this, protectedThis = makeRef(*this), cacheIdentifier, callback = WTFMove(callback)](Optional<Error>&& error) mutable {
347             if (error) {
348                 callback(makeUnexpected(error.value()));
349                 return;
350             }
351
352             auto* cache = this->cache(cacheIdentifier);
353             if (!cache) {
354                 callback(makeUnexpected(Error::Internal));
355                 return;
356             }
357             ASSERT(cache->isOpened());
358             callback(std::reference_wrapper<Cache> { *cache });
359         });
360         return;
361     }
362     callback(std::reference_wrapper<Cache> { *cache });
363 }
364
365 Cache* Engine::cache(uint64_t cacheIdentifier)
366 {
367     Cache* result = nullptr;
368     for (auto& caches : m_caches.values()) {
369         if ((result = caches->find(cacheIdentifier)))
370             break;
371     }
372     return result;
373 }
374
375 void Engine::writeFile(const String& filename, NetworkCache::Data&& data, WebCore::DOMCacheEngine::CompletionCallback&& callback)
376 {
377     if (!shouldPersist()) {
378         callback(WTF::nullopt);
379         return;
380     }
381
382     m_pendingWriteCallbacks.add(++m_pendingCallbacksCounter, WTFMove(callback));
383     m_ioQueue->dispatch([this, weakThis = makeWeakPtr(this), identifier = m_pendingCallbacksCounter, data = WTFMove(data), filename = filename.isolatedCopy()]() mutable {
384
385         String directoryPath = FileSystem::directoryName(filename);
386         if (!FileSystem::fileExists(directoryPath))
387             FileSystem::makeAllDirectories(directoryPath);
388
389         auto channel = IOChannel::open(filename, IOChannel::Type::Create);
390         channel->write(0, data, nullptr, [this, weakThis = WTFMove(weakThis), identifier](int error) mutable {
391             ASSERT(RunLoop::isMain());
392             if (!weakThis)
393                 return;
394
395             auto callback = m_pendingWriteCallbacks.take(identifier);
396             if (error) {
397                 RELEASE_LOG_ERROR(CacheStorage, "CacheStorage::Engine::writeFile failed with error %d", error);
398
399                 callback(Error::WriteDisk);
400                 return;
401             }
402             callback(WTF::nullopt);
403         });
404     });
405 }
406
407 void Engine::readFile(const String& filename, CompletionHandler<void(const NetworkCache::Data&, int error)>&& callback)
408 {
409     if (!shouldPersist()) {
410         callback(Data { }, 0);
411         return;
412     }
413
414     m_pendingReadCallbacks.add(++m_pendingCallbacksCounter, WTFMove(callback));
415     m_ioQueue->dispatch([this, weakThis = makeWeakPtr(this), identifier = m_pendingCallbacksCounter, filename = filename.isolatedCopy()]() mutable {
416         auto channel = IOChannel::open(filename, IOChannel::Type::Read);
417         if (channel->fileDescriptor() < 0) {
418             RunLoop::main().dispatch([this, weakThis = WTFMove(weakThis), identifier]() mutable {
419                 if (!weakThis)
420                     return;
421
422                 m_pendingReadCallbacks.take(identifier)(Data { }, 0);
423             });
424             return;
425         }
426
427         channel->read(0, std::numeric_limits<size_t>::max(), nullptr, [this, weakThis = WTFMove(weakThis), identifier](const Data& data, int error) mutable {
428             RELEASE_LOG_ERROR_IF(error, CacheStorage, "CacheStorage::Engine::readFile failed with error %d", error);
429
430             // FIXME: We should do the decoding in the background thread.
431             ASSERT(RunLoop::isMain());
432
433             if (!weakThis)
434                 return;
435
436             m_pendingReadCallbacks.take(identifier)(data, error);
437         });
438     });
439 }
440
441 void Engine::removeFile(const String& filename)
442 {
443     if (!shouldPersist())
444         return;
445
446     m_ioQueue->dispatch([filename = filename.isolatedCopy()]() mutable {
447         FileSystem::deleteFile(filename);
448     });
449 }
450
451 class ReadOriginsTaskCounter : public RefCounted<ReadOriginsTaskCounter> {
452 public:
453     static Ref<ReadOriginsTaskCounter> create(WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)>&& callback)
454     {
455         return adoptRef(*new ReadOriginsTaskCounter(WTFMove(callback)));
456     }
457
458     ~ReadOriginsTaskCounter()
459     {
460         m_callback(WTFMove(m_entries));
461     }
462
463     void addOrigin(WebCore::SecurityOriginData&& origin, uint64_t size)
464     {
465         m_entries.append(WebsiteData::Entry { WTFMove(origin), WebsiteDataType::DOMCache, size });
466     }
467
468 private:
469     explicit ReadOriginsTaskCounter(WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)>&& callback)
470         : m_callback(WTFMove(callback))
471     {
472     }
473
474     WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)> m_callback;
475     Vector<WebsiteData::Entry> m_entries;
476 };
477
478 void Engine::fetchEntries(bool shouldComputeSize, WTF::CompletionHandler<void(Vector<WebsiteData::Entry>)>&& completionHandler)
479 {
480     if (!shouldPersist()) {
481         auto entries = WTF::map(m_caches, [] (auto& pair) {
482             return WebsiteData::Entry { pair.value->origin().clientOrigin, WebsiteDataType::DOMCache, 0 };
483         });
484         completionHandler(WTFMove(entries));
485         return;
486     }
487
488     auto taskCounter = ReadOriginsTaskCounter::create(WTFMove(completionHandler));
489     for (auto& folderPath : FileSystem::listDirectory(m_rootPath, "*")) {
490         if (!FileSystem::fileIsDirectory(folderPath, FileSystem::ShouldFollowSymbolicLinks::No))
491             continue;
492         Caches::retrieveOriginFromDirectory(folderPath, *m_ioQueue, [protectedThis = makeRef(*this), shouldComputeSize, taskCounter = taskCounter.copyRef()] (auto&& origin) mutable {
493             ASSERT(RunLoop::isMain());
494             if (!origin)
495                 return;
496
497             if (!shouldComputeSize) {
498                 taskCounter->addOrigin(WTFMove(origin->topOrigin), 0);
499                 taskCounter->addOrigin(WTFMove(origin->clientOrigin), 0);
500                 return;
501             }
502
503             protectedThis->readCachesFromDisk(origin.value(), [origin = origin.value(), taskCounter = WTFMove(taskCounter)] (CachesOrError&& result) mutable {
504                 if (!result.has_value())
505                     return;
506                 taskCounter->addOrigin(WTFMove(origin.topOrigin), 0);
507                 taskCounter->addOrigin(WTFMove(origin.clientOrigin), result.value().get().storageSize());
508             });
509         });
510     }
511 }
512
513 void Engine::clearAllCaches(CompletionHandler<void()>&& completionHandler)
514 {
515     ASSERT(RunLoop::isMain());
516
517     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
518
519     for (auto& caches : m_caches.values())
520         caches->clear([callbackAggregator = callbackAggregator.copyRef()] { });
521
522     if (!shouldPersist())
523         return;
524
525     clearAllCachesFromDisk([callbackAggregator = WTFMove(callbackAggregator)] { });
526 }
527
528 void Engine::clearAllCachesFromDisk(CompletionHandler<void()>&& completionHandler)
529 {
530     ASSERT(RunLoop::isMain());
531
532     m_ioQueue->dispatch([path = m_rootPath.isolatedCopy(), completionHandler = WTFMove(completionHandler)]() mutable {
533         for (auto& filename : FileSystem::listDirectory(path, "*")) {
534             if (FileSystem::fileIsDirectory(filename, FileSystem::ShouldFollowSymbolicLinks::No))
535                 deleteDirectoryRecursively(filename);
536         }
537         RunLoop::main().dispatch(WTFMove(completionHandler));
538     });
539 }
540
541 void Engine::clearCachesForOrigin(const WebCore::SecurityOriginData& origin, CompletionHandler<void()>&& completionHandler)
542 {
543     ASSERT(RunLoop::isMain());
544
545     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
546
547     for (auto& keyValue : m_caches) {
548         if (keyValue.key.topOrigin == origin || keyValue.key.clientOrigin == origin)
549             keyValue.value->clear([callbackAggregator = callbackAggregator.copyRef()] { });
550     }
551
552     if (!shouldPersist())
553         return;
554
555     clearCachesForOriginFromDisk(origin, [callbackAggregator = WTFMove(callbackAggregator)] { });
556 }
557
558 void Engine::clearCachesForOriginFromDisk(const WebCore::SecurityOriginData& origin, CompletionHandler<void()>&& completionHandler)
559 {
560     ASSERT(RunLoop::isMain());
561
562     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
563
564     for (auto& folderPath : FileSystem::listDirectory(m_rootPath, "*")) {
565         if (!FileSystem::fileIsDirectory(folderPath, FileSystem::ShouldFollowSymbolicLinks::No))
566             continue;
567         Caches::retrieveOriginFromDirectory(folderPath, *m_ioQueue, [this, protectedThis = makeRef(*this), origin, callbackAggregator = callbackAggregator.copyRef(), folderPath] (Optional<WebCore::ClientOrigin>&& folderOrigin) mutable {
568             if (!folderOrigin)
569                 return;
570             if (folderOrigin->topOrigin != origin && folderOrigin->clientOrigin != origin)
571                 return;
572
573             ASSERT(folderPath == cachesRootPath(*folderOrigin));
574             deleteDirectoryRecursivelyOnBackgroundThread(folderPath, [callbackAggregator = WTFMove(callbackAggregator)] { });
575         });
576     }
577 }
578
579 void Engine::deleteDirectoryRecursivelyOnBackgroundThread(const String& path, CompletionHandler<void()>&& completionHandler)
580 {
581     ASSERT(RunLoop::isMain());
582
583     m_ioQueue->dispatch([path = path.isolatedCopy(), completionHandler = WTFMove(completionHandler)]() mutable {
584         deleteDirectoryRecursively(path);
585
586         RunLoop::main().dispatch(WTFMove(completionHandler));
587     });
588 }
589
590 void Engine::clearMemoryRepresentation(const WebCore::ClientOrigin& origin, WebCore::DOMCacheEngine::CompletionCallback&& callback)
591 {
592     readCachesFromDisk(origin, [callback = WTFMove(callback)](CachesOrError&& result) {
593         if (!result.has_value()) {
594             callback(result.error());
595             return;
596         }
597         result.value().get().clearMemoryRepresentation();
598         callback(WTF::nullopt);
599     });
600 }
601
602 void Engine::lock(uint64_t cacheIdentifier)
603 {
604     auto& counter = m_cacheLocks.ensure(cacheIdentifier, []() {
605         return 0;
606     }).iterator->value;
607
608     ++counter;
609 }
610
611 void Engine::unlock(uint64_t cacheIdentifier)
612 {
613     auto lockCount = m_cacheLocks.find(cacheIdentifier);
614     if (lockCount == m_cacheLocks.end())
615         return;
616
617     ASSERT(lockCount->value);
618     if (--lockCount->value)
619         return;
620
621     auto* cache = this->cache(cacheIdentifier);
622     if (!cache)
623         return;
624
625     cache->dispose();
626 }
627
628 String Engine::representation()
629 {
630     bool isFirst = true;
631     StringBuilder builder;
632     builder.append("{ \"path\": \"");
633     builder.append(m_rootPath);
634     builder.append("\", \"origins\": [");
635     for (auto& keyValue : m_caches) {
636         if (!isFirst)
637             builder.append(",");
638         isFirst = false;
639
640         builder.append("\n{ \"origin\" : { \"topOrigin\" : \"");
641         builder.append(keyValue.key.topOrigin.toString());
642         builder.append("\", \"clientOrigin\": \"");
643         builder.append(keyValue.key.clientOrigin.toString());
644         builder.append("\" }, \"caches\" : ");
645         keyValue.value->appendRepresentation(builder);
646         builder.append("}");
647     }
648     builder.append("]}");
649     return builder.toString();
650 }
651
652 } // namespace CacheStorage
653
654 } // namespace WebKit