1/*
2 * Copyright (C) 2008, 2010, 2011 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#ifndef ApplicationCacheStorage_h
27#define ApplicationCacheStorage_h
28
29#include "SecurityOriginHash.h"
30#include "SQLiteDatabase.h"
31#include <wtf/HashCountedSet.h>
32#include <wtf/HashSet.h>
33#include <wtf/text/StringHash.h>
34#include <wtf/text/WTFString.h>
35
36namespace WebCore {
37
38class ApplicationCache;
39class ApplicationCacheGroup;
40class ApplicationCacheHost;
41class ApplicationCacheResource;
42class URL;
43class SecurityOrigin;
44class SharedBuffer;
45template <class T> class StorageIDJournal;
46
47class ApplicationCacheStorage {
48    WTF_MAKE_NONCOPYABLE(ApplicationCacheStorage); WTF_MAKE_FAST_ALLOCATED;
49public:
50    enum FailureReason {
51        OriginQuotaReached,
52        TotalQuotaReached,
53        DiskOrOperationFailure
54    };
55
56    void setCacheDirectory(const String&);
57    const String& cacheDirectory() const;
58
59    void setMaximumSize(int64_t size);
60    int64_t maximumSize() const;
61    bool isMaximumSizeReached() const;
62    int64_t spaceNeeded(int64_t cacheToSave);
63
64    int64_t defaultOriginQuota() const { return m_defaultOriginQuota; }
65    void setDefaultOriginQuota(int64_t quota);
66    bool calculateUsageForOrigin(const SecurityOrigin*, int64_t& usage);
67    bool calculateQuotaForOrigin(const SecurityOrigin*, int64_t& quota);
68    bool calculateRemainingSizeForOriginExcludingCache(const SecurityOrigin*, ApplicationCache*, int64_t& remainingSize);
69    bool storeUpdatedQuotaForOrigin(const SecurityOrigin*, int64_t quota);
70    bool checkOriginQuota(ApplicationCacheGroup*, ApplicationCache* oldCache, ApplicationCache* newCache, int64_t& totalSpaceNeeded);
71
72    ApplicationCacheGroup* cacheGroupForURL(const URL&); // Cache to load a main resource from.
73    ApplicationCacheGroup* fallbackCacheGroupForURL(const URL&); // Cache that has a fallback entry to load a main resource from if normal loading fails.
74
75    ApplicationCacheGroup* findOrCreateCacheGroup(const URL& manifestURL);
76    ApplicationCacheGroup* findInMemoryCacheGroup(const URL& manifestURL) const;
77    void cacheGroupDestroyed(ApplicationCacheGroup*);
78    void cacheGroupMadeObsolete(ApplicationCacheGroup*);
79
80    bool storeNewestCache(ApplicationCacheGroup*, ApplicationCache* oldCache, FailureReason& failureReason);
81    bool storeNewestCache(ApplicationCacheGroup*); // Updates the cache group, but doesn't remove old cache.
82    bool store(ApplicationCacheResource*, ApplicationCache*);
83    bool storeUpdatedType(ApplicationCacheResource*, ApplicationCache*);
84
85    // Removes the group if the cache to be removed is the newest one (so, storeNewestCache() needs to be called beforehand when updating).
86    void remove(ApplicationCache*);
87
88    void empty();
89
90    static bool storeCopyOfCache(const String& cacheDirectory, ApplicationCacheHost*);
91
92    bool manifestURLs(Vector<URL>* urls);
93    bool cacheGroupSize(const String& manifestURL, int64_t* size);
94    bool deleteCacheGroup(const String& manifestURL);
95    void vacuumDatabaseFile();
96
97    void getOriginsWithCache(HashSet<RefPtr<SecurityOrigin>, SecurityOriginHash>&);
98    void deleteAllEntries();
99
100    static int64_t unknownQuota() { return -1; }
101    static int64_t noQuota() { return std::numeric_limits<int64_t>::max(); }
102private:
103    ApplicationCacheStorage();
104    PassRefPtr<ApplicationCache> loadCache(unsigned storageID);
105    ApplicationCacheGroup* loadCacheGroup(const URL& manifestURL);
106
107    typedef StorageIDJournal<ApplicationCacheResource> ResourceStorageIDJournal;
108    typedef StorageIDJournal<ApplicationCacheGroup> GroupStorageIDJournal;
109
110    bool store(ApplicationCacheGroup*, GroupStorageIDJournal*);
111    bool store(ApplicationCache*, ResourceStorageIDJournal*);
112    bool store(ApplicationCacheResource*, unsigned cacheStorageID);
113    bool deleteCacheGroupRecord(const String& manifestURL);
114
115    bool ensureOriginRecord(const SecurityOrigin*);
116    bool shouldStoreResourceAsFlatFile(ApplicationCacheResource*);
117    void deleteTables();
118    bool writeDataToUniqueFileInDirectory(SharedBuffer*, const String& directory, String& outFilename, const String& fileExtension);
119
120    void loadManifestHostHashes();
121
122    void verifySchemaVersion();
123
124    void openDatabase(bool createIfDoesNotExist);
125
126    bool executeStatement(SQLiteStatement&);
127    bool executeSQLCommand(const String&);
128
129    void checkForMaxSizeReached();
130    void checkForDeletedResources();
131    long long flatFileAreaSize();
132
133    String m_cacheDirectory;
134    String m_cacheFile;
135
136    int64_t m_maximumSize;
137    bool m_isMaximumSizeReached;
138
139    int64_t m_defaultOriginQuota;
140
141    SQLiteDatabase m_database;
142
143    // In order to quickly determine if a given resource exists in an application cache,
144    // we keep a hash set of the hosts of the manifest URLs of all non-obsolete cache groups.
145    HashCountedSet<unsigned, AlreadyHashed> m_cacheHostSet;
146
147    typedef HashMap<String, ApplicationCacheGroup*> CacheGroupMap;
148    CacheGroupMap m_cachesInMemory; // Excludes obsolete cache groups.
149
150    friend class WTF::NeverDestroyed<ApplicationCacheStorage>;
151};
152
153ApplicationCacheStorage& cacheStorage();
154
155} // namespace WebCore
156
157#endif // ApplicationCacheStorage_h
158