1 /*
2 * Copyright (C) 2008, 2009 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 "ApplicationCacheStorage.h"
28
29 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
30
31 #include "ApplicationCache.h"
32 #include "ApplicationCacheHost.h"
33 #include "ApplicationCacheGroup.h"
34 #include "ApplicationCacheResource.h"
35 #include "CString.h"
36 #include "FileSystem.h"
37 #include "KURL.h"
38 #include "SQLiteStatement.h"
39 #include "SQLiteTransaction.h"
40 #include <wtf/StdLibExtras.h>
41 #include <wtf/StringExtras.h>
42
43 using namespace std;
44
45 namespace WebCore {
46
47 template <class T>
48 class StorageIDJournal {
49 public:
~StorageIDJournal()50 ~StorageIDJournal()
51 {
52 size_t size = m_records.size();
53 for (size_t i = 0; i < size; ++i)
54 m_records[i].restore();
55 }
56
add(T * resource,unsigned storageID)57 void add(T* resource, unsigned storageID)
58 {
59 m_records.append(Record(resource, storageID));
60 }
61
commit()62 void commit()
63 {
64 m_records.clear();
65 }
66
67 private:
68 class Record {
69 public:
Record()70 Record() : m_resource(0), m_storageID(0) { }
Record(T * resource,unsigned storageID)71 Record(T* resource, unsigned storageID) : m_resource(resource), m_storageID(storageID) { }
72
restore()73 void restore()
74 {
75 m_resource->setStorageID(m_storageID);
76 }
77
78 private:
79 T* m_resource;
80 unsigned m_storageID;
81 };
82
83 Vector<Record> m_records;
84 };
85
urlHostHash(const KURL & url)86 static unsigned urlHostHash(const KURL& url)
87 {
88 unsigned hostStart = url.hostStart();
89 unsigned hostEnd = url.hostEnd();
90
91 return AlreadyHashed::avoidDeletedValue(StringImpl::computeHash(url.string().characters() + hostStart, hostEnd - hostStart));
92 }
93
loadCacheGroup(const KURL & manifestURL)94 ApplicationCacheGroup* ApplicationCacheStorage::loadCacheGroup(const KURL& manifestURL)
95 {
96 openDatabase(false);
97 if (!m_database.isOpen())
98 return 0;
99
100 SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL AND manifestURL=?");
101 if (statement.prepare() != SQLResultOk)
102 return 0;
103
104 statement.bindText(1, manifestURL);
105
106 int result = statement.step();
107 if (result == SQLResultDone)
108 return 0;
109
110 if (result != SQLResultRow) {
111 LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg());
112 return 0;
113 }
114
115 unsigned newestCacheStorageID = static_cast<unsigned>(statement.getColumnInt64(2));
116
117 RefPtr<ApplicationCache> cache = loadCache(newestCacheStorageID);
118 if (!cache)
119 return 0;
120
121 ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL);
122
123 group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
124 group->setNewestCache(cache.release());
125
126 return group;
127 }
128
findOrCreateCacheGroup(const KURL & manifestURL)129 ApplicationCacheGroup* ApplicationCacheStorage::findOrCreateCacheGroup(const KURL& manifestURL)
130 {
131 ASSERT(!manifestURL.hasFragmentIdentifier());
132
133 std::pair<CacheGroupMap::iterator, bool> result = m_cachesInMemory.add(manifestURL, 0);
134
135 if (!result.second) {
136 ASSERT(result.first->second);
137 return result.first->second;
138 }
139
140 // Look up the group in the database
141 ApplicationCacheGroup* group = loadCacheGroup(manifestURL);
142
143 // If the group was not found we need to create it
144 if (!group) {
145 group = new ApplicationCacheGroup(manifestURL);
146 m_cacheHostSet.add(urlHostHash(manifestURL));
147 }
148
149 result.first->second = group;
150
151 return group;
152 }
153
loadManifestHostHashes()154 void ApplicationCacheStorage::loadManifestHostHashes()
155 {
156 static bool hasLoadedHashes = false;
157
158 if (hasLoadedHashes)
159 return;
160
161 // We set this flag to true before the database has been opened
162 // to avoid trying to open the database over and over if it doesn't exist.
163 hasLoadedHashes = true;
164
165 openDatabase(false);
166 if (!m_database.isOpen())
167 return;
168
169 // Fetch the host hashes.
170 SQLiteStatement statement(m_database, "SELECT manifestHostHash FROM CacheGroups");
171 if (statement.prepare() != SQLResultOk)
172 return;
173
174 int result;
175 while ((result = statement.step()) == SQLResultRow)
176 m_cacheHostSet.add(static_cast<unsigned>(statement.getColumnInt64(0)));
177 }
178
cacheGroupForURL(const KURL & url)179 ApplicationCacheGroup* ApplicationCacheStorage::cacheGroupForURL(const KURL& url)
180 {
181 ASSERT(!url.hasFragmentIdentifier());
182
183 loadManifestHostHashes();
184
185 // Hash the host name and see if there's a manifest with the same host.
186 if (!m_cacheHostSet.contains(urlHostHash(url)))
187 return 0;
188
189 // Check if a cache already exists in memory.
190 CacheGroupMap::const_iterator end = m_cachesInMemory.end();
191 for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) {
192 ApplicationCacheGroup* group = it->second;
193
194 ASSERT(!group->isObsolete());
195
196 if (!protocolHostAndPortAreEqual(url, group->manifestURL()))
197 continue;
198
199 if (ApplicationCache* cache = group->newestCache()) {
200 ApplicationCacheResource* resource = cache->resourceForURL(url);
201 if (!resource)
202 continue;
203 if (resource->type() & ApplicationCacheResource::Foreign)
204 continue;
205 return group;
206 }
207 }
208
209 if (!m_database.isOpen())
210 return 0;
211
212 // Check the database. Look for all cache groups with a newest cache.
213 SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL");
214 if (statement.prepare() != SQLResultOk)
215 return 0;
216
217 int result;
218 while ((result = statement.step()) == SQLResultRow) {
219 KURL manifestURL = KURL(statement.getColumnText(1));
220
221 if (m_cachesInMemory.contains(manifestURL))
222 continue;
223
224 if (!protocolHostAndPortAreEqual(url, manifestURL))
225 continue;
226
227 // We found a cache group that matches. Now check if the newest cache has a resource with
228 // a matching URL.
229 unsigned newestCacheID = static_cast<unsigned>(statement.getColumnInt64(2));
230 RefPtr<ApplicationCache> cache = loadCache(newestCacheID);
231 if (!cache)
232 continue;
233
234 ApplicationCacheResource* resource = cache->resourceForURL(url);
235 if (!resource)
236 continue;
237 if (resource->type() & ApplicationCacheResource::Foreign)
238 continue;
239
240 ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL);
241
242 group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
243 group->setNewestCache(cache.release());
244
245 m_cachesInMemory.set(group->manifestURL(), group);
246
247 return group;
248 }
249
250 if (result != SQLResultDone)
251 LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg());
252
253 return 0;
254 }
255
fallbackCacheGroupForURL(const KURL & url)256 ApplicationCacheGroup* ApplicationCacheStorage::fallbackCacheGroupForURL(const KURL& url)
257 {
258 ASSERT(!url.hasFragmentIdentifier());
259
260 // Check if an appropriate cache already exists in memory.
261 CacheGroupMap::const_iterator end = m_cachesInMemory.end();
262 for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) {
263 ApplicationCacheGroup* group = it->second;
264
265 ASSERT(!group->isObsolete());
266
267 if (ApplicationCache* cache = group->newestCache()) {
268 KURL fallbackURL;
269 if (!cache->urlMatchesFallbackNamespace(url, &fallbackURL))
270 continue;
271 if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign)
272 continue;
273 return group;
274 }
275 }
276
277 if (!m_database.isOpen())
278 return 0;
279
280 // Check the database. Look for all cache groups with a newest cache.
281 SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL");
282 if (statement.prepare() != SQLResultOk)
283 return 0;
284
285 int result;
286 while ((result = statement.step()) == SQLResultRow) {
287 KURL manifestURL = KURL(statement.getColumnText(1));
288
289 if (m_cachesInMemory.contains(manifestURL))
290 continue;
291
292 // Fallback namespaces always have the same origin as manifest URL, so we can avoid loading caches that cannot match.
293 if (!protocolHostAndPortAreEqual(url, manifestURL))
294 continue;
295
296 // We found a cache group that matches. Now check if the newest cache has a resource with
297 // a matching fallback namespace.
298 unsigned newestCacheID = static_cast<unsigned>(statement.getColumnInt64(2));
299 RefPtr<ApplicationCache> cache = loadCache(newestCacheID);
300
301 KURL fallbackURL;
302 if (!cache->urlMatchesFallbackNamespace(url, &fallbackURL))
303 continue;
304 if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign)
305 continue;
306
307 ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL);
308
309 group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
310 group->setNewestCache(cache.release());
311
312 m_cachesInMemory.set(group->manifestURL(), group);
313
314 return group;
315 }
316
317 if (result != SQLResultDone)
318 LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg());
319
320 return 0;
321 }
322
cacheGroupDestroyed(ApplicationCacheGroup * group)323 void ApplicationCacheStorage::cacheGroupDestroyed(ApplicationCacheGroup* group)
324 {
325 if (group->isObsolete()) {
326 ASSERT(!group->storageID());
327 ASSERT(m_cachesInMemory.get(group->manifestURL()) != group);
328 return;
329 }
330
331 ASSERT(m_cachesInMemory.get(group->manifestURL()) == group);
332
333 m_cachesInMemory.remove(group->manifestURL());
334
335 // If the cache group is half-created, we don't want it in the saved set (as it is not stored in database).
336 if (!group->storageID())
337 m_cacheHostSet.remove(urlHostHash(group->manifestURL()));
338 }
339
cacheGroupMadeObsolete(ApplicationCacheGroup * group)340 void ApplicationCacheStorage::cacheGroupMadeObsolete(ApplicationCacheGroup* group)
341 {
342 ASSERT(m_cachesInMemory.get(group->manifestURL()) == group);
343 ASSERT(m_cacheHostSet.contains(urlHostHash(group->manifestURL())));
344
345 if (ApplicationCache* newestCache = group->newestCache())
346 remove(newestCache);
347
348 m_cachesInMemory.remove(group->manifestURL());
349 m_cacheHostSet.remove(urlHostHash(group->manifestURL()));
350 }
351
setCacheDirectory(const String & cacheDirectory)352 void ApplicationCacheStorage::setCacheDirectory(const String& cacheDirectory)
353 {
354 ASSERT(m_cacheDirectory.isNull());
355 ASSERT(!cacheDirectory.isNull());
356
357 m_cacheDirectory = cacheDirectory;
358 }
359
cacheDirectory() const360 const String& ApplicationCacheStorage::cacheDirectory() const
361 {
362 return m_cacheDirectory;
363 }
364
setMaximumSize(int64_t size)365 void ApplicationCacheStorage::setMaximumSize(int64_t size)
366 {
367 m_maximumSize = size;
368 }
369
maximumSize() const370 int64_t ApplicationCacheStorage::maximumSize() const
371 {
372 return m_maximumSize;
373 }
374
isMaximumSizeReached() const375 bool ApplicationCacheStorage::isMaximumSizeReached() const
376 {
377 return m_isMaximumSizeReached;
378 }
379
spaceNeeded(int64_t cacheToSave)380 int64_t ApplicationCacheStorage::spaceNeeded(int64_t cacheToSave)
381 {
382 int64_t spaceNeeded = 0;
383 long long fileSize = 0;
384 if (!getFileSize(m_cacheFile, fileSize))
385 return 0;
386
387 int64_t currentSize = fileSize;
388
389 // Determine the amount of free space we have available.
390 int64_t totalAvailableSize = 0;
391 if (m_maximumSize < currentSize) {
392 // The max size is smaller than the actual size of the app cache file.
393 // This can happen if the client previously imposed a larger max size
394 // value and the app cache file has already grown beyond the current
395 // max size value.
396 // The amount of free space is just the amount of free space inside
397 // the database file. Note that this is always 0 if SQLite is compiled
398 // with AUTO_VACUUM = 1.
399 totalAvailableSize = m_database.freeSpaceSize();
400 } else {
401 // The max size is the same or larger than the current size.
402 // The amount of free space available is the amount of free space
403 // inside the database file plus the amount we can grow until we hit
404 // the max size.
405 totalAvailableSize = (m_maximumSize - currentSize) + m_database.freeSpaceSize();
406 }
407
408 // The space needed to be freed in order to accomodate the failed cache is
409 // the size of the failed cache minus any already available free space.
410 spaceNeeded = cacheToSave - totalAvailableSize;
411 // The space needed value must be positive (or else the total already
412 // available free space would be larger than the size of the failed cache and
413 // saving of the cache should have never failed).
414 ASSERT(spaceNeeded);
415 return spaceNeeded;
416 }
417
executeSQLCommand(const String & sql)418 bool ApplicationCacheStorage::executeSQLCommand(const String& sql)
419 {
420 ASSERT(m_database.isOpen());
421
422 bool result = m_database.executeCommand(sql);
423 if (!result)
424 LOG_ERROR("Application Cache Storage: failed to execute statement \"%s\" error \"%s\"",
425 sql.utf8().data(), m_database.lastErrorMsg());
426
427 return result;
428 }
429
430 static const int schemaVersion = 4;
431
verifySchemaVersion()432 void ApplicationCacheStorage::verifySchemaVersion()
433 {
434 int version = SQLiteStatement(m_database, "PRAGMA user_version").getColumnInt(0);
435 if (version == schemaVersion)
436 return;
437
438 m_database.clearAllTables();
439
440 // Update user version.
441 SQLiteTransaction setDatabaseVersion(m_database);
442 setDatabaseVersion.begin();
443
444 char userVersionSQL[32];
445 int unusedNumBytes = snprintf(userVersionSQL, sizeof(userVersionSQL), "PRAGMA user_version=%d", schemaVersion);
446 ASSERT_UNUSED(unusedNumBytes, static_cast<int>(sizeof(userVersionSQL)) >= unusedNumBytes);
447
448 SQLiteStatement statement(m_database, userVersionSQL);
449 if (statement.prepare() != SQLResultOk)
450 return;
451
452 executeStatement(statement);
453 setDatabaseVersion.commit();
454 }
455
openDatabase(bool createIfDoesNotExist)456 void ApplicationCacheStorage::openDatabase(bool createIfDoesNotExist)
457 {
458 if (m_database.isOpen())
459 return;
460
461 // The cache directory should never be null, but if it for some weird reason is we bail out.
462 if (m_cacheDirectory.isNull())
463 return;
464
465 m_cacheFile = pathByAppendingComponent(m_cacheDirectory, "ApplicationCache.db");
466 if (!createIfDoesNotExist && !fileExists(m_cacheFile))
467 return;
468
469 makeAllDirectories(m_cacheDirectory);
470 m_database.open(m_cacheFile);
471
472 if (!m_database.isOpen())
473 return;
474
475 verifySchemaVersion();
476
477 // Create tables
478 executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheGroups (id INTEGER PRIMARY KEY AUTOINCREMENT, "
479 "manifestHostHash INTEGER NOT NULL ON CONFLICT FAIL, manifestURL TEXT UNIQUE ON CONFLICT FAIL, newestCache INTEGER)");
480 executeSQLCommand("CREATE TABLE IF NOT EXISTS Caches (id INTEGER PRIMARY KEY AUTOINCREMENT, cacheGroup INTEGER, size INTEGER)");
481 executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheWhitelistURLs (url TEXT NOT NULL ON CONFLICT FAIL, cache INTEGER NOT NULL ON CONFLICT FAIL)");
482 executeSQLCommand("CREATE TABLE IF NOT EXISTS FallbackURLs (namespace TEXT NOT NULL ON CONFLICT FAIL, fallbackURL TEXT NOT NULL ON CONFLICT FAIL, "
483 "cache INTEGER NOT NULL ON CONFLICT FAIL)");
484 executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheEntries (cache INTEGER NOT NULL ON CONFLICT FAIL, type INTEGER, resource INTEGER NOT NULL)");
485 executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheResources (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL ON CONFLICT FAIL, "
486 "statusCode INTEGER NOT NULL, responseURL TEXT NOT NULL, mimeType TEXT, textEncodingName TEXT, headers TEXT, data INTEGER NOT NULL ON CONFLICT FAIL)");
487 executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheResourceData (id INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB)");
488
489 // When a cache is deleted, all its entries and its whitelist should be deleted.
490 executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheDeleted AFTER DELETE ON Caches"
491 " FOR EACH ROW BEGIN"
492 " DELETE FROM CacheEntries WHERE cache = OLD.id;"
493 " DELETE FROM CacheWhitelistURLs WHERE cache = OLD.id;"
494 " DELETE FROM FallbackURLs WHERE cache = OLD.id;"
495 " END");
496
497 // When a cache entry is deleted, its resource should also be deleted.
498 executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheEntryDeleted AFTER DELETE ON CacheEntries"
499 " FOR EACH ROW BEGIN"
500 " DELETE FROM CacheResources WHERE id = OLD.resource;"
501 " END");
502
503 // When a cache resource is deleted, its data blob should also be deleted.
504 executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheResourceDeleted AFTER DELETE ON CacheResources"
505 " FOR EACH ROW BEGIN"
506 " DELETE FROM CacheResourceData WHERE id = OLD.data;"
507 " END");
508 }
509
executeStatement(SQLiteStatement & statement)510 bool ApplicationCacheStorage::executeStatement(SQLiteStatement& statement)
511 {
512 bool result = statement.executeCommand();
513 if (!result)
514 LOG_ERROR("Application Cache Storage: failed to execute statement \"%s\" error \"%s\"",
515 statement.query().utf8().data(), m_database.lastErrorMsg());
516
517 return result;
518 }
519
store(ApplicationCacheGroup * group,GroupStorageIDJournal * journal)520 bool ApplicationCacheStorage::store(ApplicationCacheGroup* group, GroupStorageIDJournal* journal)
521 {
522 ASSERT(group->storageID() == 0);
523 ASSERT(journal);
524
525 SQLiteStatement statement(m_database, "INSERT INTO CacheGroups (manifestHostHash, manifestURL) VALUES (?, ?)");
526 if (statement.prepare() != SQLResultOk)
527 return false;
528
529 statement.bindInt64(1, urlHostHash(group->manifestURL()));
530 statement.bindText(2, group->manifestURL());
531
532 if (!executeStatement(statement))
533 return false;
534
535 group->setStorageID(static_cast<unsigned>(m_database.lastInsertRowID()));
536 journal->add(group, 0);
537 return true;
538 }
539
store(ApplicationCache * cache,ResourceStorageIDJournal * storageIDJournal)540 bool ApplicationCacheStorage::store(ApplicationCache* cache, ResourceStorageIDJournal* storageIDJournal)
541 {
542 ASSERT(cache->storageID() == 0);
543 ASSERT(cache->group()->storageID() != 0);
544 ASSERT(storageIDJournal);
545
546 SQLiteStatement statement(m_database, "INSERT INTO Caches (cacheGroup, size) VALUES (?, ?)");
547 if (statement.prepare() != SQLResultOk)
548 return false;
549
550 statement.bindInt64(1, cache->group()->storageID());
551 statement.bindInt64(2, cache->estimatedSizeInStorage());
552
553 if (!executeStatement(statement))
554 return false;
555
556 unsigned cacheStorageID = static_cast<unsigned>(m_database.lastInsertRowID());
557
558 // Store all resources
559 {
560 ApplicationCache::ResourceMap::const_iterator end = cache->end();
561 for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) {
562 unsigned oldStorageID = it->second->storageID();
563 if (!store(it->second.get(), cacheStorageID))
564 return false;
565
566 // Storing the resource succeeded. Log its old storageID in case
567 // it needs to be restored later.
568 storageIDJournal->add(it->second.get(), oldStorageID);
569 }
570 }
571
572 // Store the online whitelist
573 const Vector<KURL>& onlineWhitelist = cache->onlineWhitelist();
574 {
575 size_t whitelistSize = onlineWhitelist.size();
576 for (size_t i = 0; i < whitelistSize; ++i) {
577 SQLiteStatement statement(m_database, "INSERT INTO CacheWhitelistURLs (url, cache) VALUES (?, ?)");
578 statement.prepare();
579
580 statement.bindText(1, onlineWhitelist[i]);
581 statement.bindInt64(2, cacheStorageID);
582
583 if (!executeStatement(statement))
584 return false;
585 }
586 }
587
588 // Store fallback URLs.
589 const FallbackURLVector& fallbackURLs = cache->fallbackURLs();
590 {
591 size_t fallbackCount = fallbackURLs.size();
592 for (size_t i = 0; i < fallbackCount; ++i) {
593 SQLiteStatement statement(m_database, "INSERT INTO FallbackURLs (namespace, fallbackURL, cache) VALUES (?, ?, ?)");
594 statement.prepare();
595
596 statement.bindText(1, fallbackURLs[i].first);
597 statement.bindText(2, fallbackURLs[i].second);
598 statement.bindInt64(3, cacheStorageID);
599
600 if (!executeStatement(statement))
601 return false;
602 }
603 }
604
605 cache->setStorageID(cacheStorageID);
606 return true;
607 }
608
store(ApplicationCacheResource * resource,unsigned cacheStorageID)609 bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, unsigned cacheStorageID)
610 {
611 ASSERT(cacheStorageID);
612 ASSERT(!resource->storageID());
613
614 openDatabase(true);
615
616 // First, insert the data
617 SQLiteStatement dataStatement(m_database, "INSERT INTO CacheResourceData (data) VALUES (?)");
618 if (dataStatement.prepare() != SQLResultOk)
619 return false;
620
621 if (resource->data()->size())
622 dataStatement.bindBlob(1, resource->data()->data(), resource->data()->size());
623
624 if (!dataStatement.executeCommand())
625 return false;
626
627 unsigned dataId = static_cast<unsigned>(m_database.lastInsertRowID());
628
629 // Then, insert the resource
630
631 // Serialize the headers
632 Vector<UChar> stringBuilder;
633
634 HTTPHeaderMap::const_iterator end = resource->response().httpHeaderFields().end();
635 for (HTTPHeaderMap::const_iterator it = resource->response().httpHeaderFields().begin(); it!= end; ++it) {
636 stringBuilder.append(it->first.characters(), it->first.length());
637 stringBuilder.append((UChar)':');
638 stringBuilder.append(it->second.characters(), it->second.length());
639 stringBuilder.append((UChar)'\n');
640 }
641
642 String headers = String::adopt(stringBuilder);
643
644 SQLiteStatement resourceStatement(m_database, "INSERT INTO CacheResources (url, statusCode, responseURL, headers, data, mimeType, textEncodingName) VALUES (?, ?, ?, ?, ?, ?, ?)");
645 if (resourceStatement.prepare() != SQLResultOk)
646 return false;
647
648 // The same ApplicationCacheResource are used in ApplicationCacheResource::size()
649 // to calculate the approximate size of an ApplicationCacheResource object. If
650 // you change the code below, please also change ApplicationCacheResource::size().
651 resourceStatement.bindText(1, resource->url());
652 resourceStatement.bindInt64(2, resource->response().httpStatusCode());
653 resourceStatement.bindText(3, resource->response().url());
654 resourceStatement.bindText(4, headers);
655 resourceStatement.bindInt64(5, dataId);
656 resourceStatement.bindText(6, resource->response().mimeType());
657 resourceStatement.bindText(7, resource->response().textEncodingName());
658
659 if (!executeStatement(resourceStatement))
660 return false;
661
662 unsigned resourceId = static_cast<unsigned>(m_database.lastInsertRowID());
663
664 // Finally, insert the cache entry
665 SQLiteStatement entryStatement(m_database, "INSERT INTO CacheEntries (cache, type, resource) VALUES (?, ?, ?)");
666 if (entryStatement.prepare() != SQLResultOk)
667 return false;
668
669 entryStatement.bindInt64(1, cacheStorageID);
670 entryStatement.bindInt64(2, resource->type());
671 entryStatement.bindInt64(3, resourceId);
672
673 if (!executeStatement(entryStatement))
674 return false;
675
676 resource->setStorageID(resourceId);
677 return true;
678 }
679
storeUpdatedType(ApplicationCacheResource * resource,ApplicationCache * cache)680 bool ApplicationCacheStorage::storeUpdatedType(ApplicationCacheResource* resource, ApplicationCache* cache)
681 {
682 ASSERT_UNUSED(cache, cache->storageID());
683 ASSERT(resource->storageID());
684
685 // First, insert the data
686 SQLiteStatement entryStatement(m_database, "UPDATE CacheEntries SET type=? WHERE resource=?");
687 if (entryStatement.prepare() != SQLResultOk)
688 return false;
689
690 entryStatement.bindInt64(1, resource->type());
691 entryStatement.bindInt64(2, resource->storageID());
692
693 return executeStatement(entryStatement);
694 }
695
store(ApplicationCacheResource * resource,ApplicationCache * cache)696 bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, ApplicationCache* cache)
697 {
698 ASSERT(cache->storageID());
699
700 openDatabase(true);
701
702 m_isMaximumSizeReached = false;
703 m_database.setMaximumSize(m_maximumSize);
704
705 SQLiteTransaction storeResourceTransaction(m_database);
706 storeResourceTransaction.begin();
707
708 if (!store(resource, cache->storageID())) {
709 checkForMaxSizeReached();
710 return false;
711 }
712
713 // A resource was added to the cache. Update the total data size for the cache.
714 SQLiteStatement sizeUpdateStatement(m_database, "UPDATE Caches SET size=size+? WHERE id=?");
715 if (sizeUpdateStatement.prepare() != SQLResultOk)
716 return false;
717
718 sizeUpdateStatement.bindInt64(1, resource->estimatedSizeInStorage());
719 sizeUpdateStatement.bindInt64(2, cache->storageID());
720
721 if (!executeStatement(sizeUpdateStatement))
722 return false;
723
724 storeResourceTransaction.commit();
725 return true;
726 }
727
storeNewestCache(ApplicationCacheGroup * group)728 bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group)
729 {
730 openDatabase(true);
731
732 m_isMaximumSizeReached = false;
733 m_database.setMaximumSize(m_maximumSize);
734
735 SQLiteTransaction storeCacheTransaction(m_database);
736
737 storeCacheTransaction.begin();
738
739 GroupStorageIDJournal groupStorageIDJournal;
740 if (!group->storageID()) {
741 // Store the group
742 if (!store(group, &groupStorageIDJournal)) {
743 checkForMaxSizeReached();
744 return false;
745 }
746 }
747
748 ASSERT(group->newestCache());
749 ASSERT(!group->isObsolete());
750 ASSERT(!group->newestCache()->storageID());
751
752 // Log the storageID changes to the in-memory resource objects. The journal
753 // object will roll them back automatically in case a database operation
754 // fails and this method returns early.
755 ResourceStorageIDJournal resourceStorageIDJournal;
756
757 // Store the newest cache
758 if (!store(group->newestCache(), &resourceStorageIDJournal)) {
759 checkForMaxSizeReached();
760 return false;
761 }
762
763 // Update the newest cache in the group.
764
765 SQLiteStatement statement(m_database, "UPDATE CacheGroups SET newestCache=? WHERE id=?");
766 if (statement.prepare() != SQLResultOk)
767 return false;
768
769 statement.bindInt64(1, group->newestCache()->storageID());
770 statement.bindInt64(2, group->storageID());
771
772 if (!executeStatement(statement))
773 return false;
774
775 groupStorageIDJournal.commit();
776 resourceStorageIDJournal.commit();
777 storeCacheTransaction.commit();
778 return true;
779 }
780
parseHeader(const UChar * header,size_t headerLength,ResourceResponse & response)781 static inline void parseHeader(const UChar* header, size_t headerLength, ResourceResponse& response)
782 {
783 int pos = find(header, headerLength, ':');
784 ASSERT(pos != -1);
785
786 AtomicString headerName = AtomicString(header, pos);
787 String headerValue = String(header + pos + 1, headerLength - pos - 1);
788
789 response.setHTTPHeaderField(headerName, headerValue);
790 }
791
parseHeaders(const String & headers,ResourceResponse & response)792 static inline void parseHeaders(const String& headers, ResourceResponse& response)
793 {
794 int startPos = 0;
795 int endPos;
796 while ((endPos = headers.find('\n', startPos)) != -1) {
797 ASSERT(startPos != endPos);
798
799 parseHeader(headers.characters() + startPos, endPos - startPos, response);
800
801 startPos = endPos + 1;
802 }
803
804 if (startPos != static_cast<int>(headers.length()))
805 parseHeader(headers.characters(), headers.length(), response);
806 }
807
loadCache(unsigned storageID)808 PassRefPtr<ApplicationCache> ApplicationCacheStorage::loadCache(unsigned storageID)
809 {
810 SQLiteStatement cacheStatement(m_database,
811 "SELECT url, type, mimeType, textEncodingName, headers, CacheResourceData.data FROM CacheEntries INNER JOIN CacheResources ON CacheEntries.resource=CacheResources.id "
812 "INNER JOIN CacheResourceData ON CacheResourceData.id=CacheResources.data WHERE CacheEntries.cache=?");
813 if (cacheStatement.prepare() != SQLResultOk) {
814 LOG_ERROR("Could not prepare cache statement, error \"%s\"", m_database.lastErrorMsg());
815 return 0;
816 }
817
818 cacheStatement.bindInt64(1, storageID);
819
820 RefPtr<ApplicationCache> cache = ApplicationCache::create();
821
822 int result;
823 while ((result = cacheStatement.step()) == SQLResultRow) {
824 KURL url(cacheStatement.getColumnText(0));
825
826 unsigned type = static_cast<unsigned>(cacheStatement.getColumnInt64(1));
827
828 Vector<char> blob;
829 cacheStatement.getColumnBlobAsVector(5, blob);
830
831 RefPtr<SharedBuffer> data = SharedBuffer::adoptVector(blob);
832
833 String mimeType = cacheStatement.getColumnText(2);
834 String textEncodingName = cacheStatement.getColumnText(3);
835
836 ResourceResponse response(url, mimeType, data->size(), textEncodingName, "");
837
838 String headers = cacheStatement.getColumnText(4);
839 parseHeaders(headers, response);
840
841 RefPtr<ApplicationCacheResource> resource = ApplicationCacheResource::create(url, response, type, data.release());
842
843 if (type & ApplicationCacheResource::Manifest)
844 cache->setManifestResource(resource.release());
845 else
846 cache->addResource(resource.release());
847 }
848
849 if (result != SQLResultDone)
850 LOG_ERROR("Could not load cache resources, error \"%s\"", m_database.lastErrorMsg());
851
852 // Load the online whitelist
853 SQLiteStatement whitelistStatement(m_database, "SELECT url FROM CacheWhitelistURLs WHERE cache=?");
854 if (whitelistStatement.prepare() != SQLResultOk)
855 return 0;
856 whitelistStatement.bindInt64(1, storageID);
857
858 Vector<KURL> whitelist;
859 while ((result = whitelistStatement.step()) == SQLResultRow)
860 whitelist.append(whitelistStatement.getColumnText(0));
861
862 if (result != SQLResultDone)
863 LOG_ERROR("Could not load cache online whitelist, error \"%s\"", m_database.lastErrorMsg());
864
865 cache->setOnlineWhitelist(whitelist);
866
867 // Load fallback URLs.
868 SQLiteStatement fallbackStatement(m_database, "SELECT namespace, fallbackURL FROM FallbackURLs WHERE cache=?");
869 if (fallbackStatement.prepare() != SQLResultOk)
870 return 0;
871 fallbackStatement.bindInt64(1, storageID);
872
873 FallbackURLVector fallbackURLs;
874 while ((result = fallbackStatement.step()) == SQLResultRow)
875 fallbackURLs.append(make_pair(fallbackStatement.getColumnText(0), fallbackStatement.getColumnText(1)));
876
877 if (result != SQLResultDone)
878 LOG_ERROR("Could not load fallback URLs, error \"%s\"", m_database.lastErrorMsg());
879
880 cache->setFallbackURLs(fallbackURLs);
881
882 cache->setStorageID(storageID);
883
884 return cache.release();
885 }
886
remove(ApplicationCache * cache)887 void ApplicationCacheStorage::remove(ApplicationCache* cache)
888 {
889 if (!cache->storageID())
890 return;
891
892 openDatabase(false);
893 if (!m_database.isOpen())
894 return;
895
896 ASSERT(cache->group());
897 ASSERT(cache->group()->storageID());
898
899 // All associated data will be deleted by database triggers.
900 SQLiteStatement statement(m_database, "DELETE FROM Caches WHERE id=?");
901 if (statement.prepare() != SQLResultOk)
902 return;
903
904 statement.bindInt64(1, cache->storageID());
905 executeStatement(statement);
906
907 cache->clearStorageID();
908
909 if (cache->group()->newestCache() == cache) {
910 // Currently, there are no triggers on the cache group, which is why the cache had to be removed separately above.
911 SQLiteStatement groupStatement(m_database, "DELETE FROM CacheGroups WHERE id=?");
912 if (groupStatement.prepare() != SQLResultOk)
913 return;
914
915 groupStatement.bindInt64(1, cache->group()->storageID());
916 executeStatement(groupStatement);
917
918 cache->group()->clearStorageID();
919 }
920 }
921
empty()922 void ApplicationCacheStorage::empty()
923 {
924 openDatabase(false);
925
926 if (!m_database.isOpen())
927 return;
928
929 // Clear cache groups, caches and cache resources.
930 executeSQLCommand("DELETE FROM CacheGroups");
931 executeSQLCommand("DELETE FROM Caches");
932
933 // Clear the storage IDs for the caches in memory.
934 // The caches will still work, but cached resources will not be saved to disk
935 // until a cache update process has been initiated.
936 CacheGroupMap::const_iterator end = m_cachesInMemory.end();
937 for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it)
938 it->second->clearStorageID();
939 }
940
storeCopyOfCache(const String & cacheDirectory,ApplicationCacheHost * cacheHost)941 bool ApplicationCacheStorage::storeCopyOfCache(const String& cacheDirectory, ApplicationCacheHost* cacheHost)
942 {
943 ApplicationCache* cache = cacheHost->applicationCache();
944 if (!cache)
945 return true;
946
947 // Create a new cache.
948 RefPtr<ApplicationCache> cacheCopy = ApplicationCache::create();
949
950 cacheCopy->setOnlineWhitelist(cache->onlineWhitelist());
951 cacheCopy->setFallbackURLs(cache->fallbackURLs());
952
953 // Traverse the cache and add copies of all resources.
954 ApplicationCache::ResourceMap::const_iterator end = cache->end();
955 for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) {
956 ApplicationCacheResource* resource = it->second.get();
957
958 RefPtr<ApplicationCacheResource> resourceCopy = ApplicationCacheResource::create(resource->url(), resource->response(), resource->type(), resource->data());
959
960 cacheCopy->addResource(resourceCopy.release());
961 }
962
963 // Now create a new cache group.
964 OwnPtr<ApplicationCacheGroup> groupCopy(new ApplicationCacheGroup(cache->group()->manifestURL(), true));
965
966 groupCopy->setNewestCache(cacheCopy);
967
968 ApplicationCacheStorage copyStorage;
969 copyStorage.setCacheDirectory(cacheDirectory);
970
971 // Empty the cache in case something was there before.
972 copyStorage.empty();
973
974 return copyStorage.storeNewestCache(groupCopy.get());
975 }
976
manifestURLs(Vector<KURL> * urls)977 bool ApplicationCacheStorage::manifestURLs(Vector<KURL>* urls)
978 {
979 ASSERT(urls);
980 openDatabase(false);
981 if (!m_database.isOpen())
982 return false;
983
984 SQLiteStatement selectURLs(m_database, "SELECT manifestURL FROM CacheGroups");
985
986 if (selectURLs.prepare() != SQLResultOk)
987 return false;
988
989 while (selectURLs.step() == SQLResultRow)
990 urls->append(selectURLs.getColumnText(0));
991
992 return true;
993 }
994
cacheGroupSize(const String & manifestURL,int64_t * size)995 bool ApplicationCacheStorage::cacheGroupSize(const String& manifestURL, int64_t* size)
996 {
997 ASSERT(size);
998 openDatabase(false);
999 if (!m_database.isOpen())
1000 return false;
1001
1002 SQLiteStatement statement(m_database, "SELECT sum(Caches.size) FROM Caches INNER JOIN CacheGroups ON Caches.cacheGroup=CacheGroups.id WHERE CacheGroups.manifestURL=?");
1003 if (statement.prepare() != SQLResultOk)
1004 return false;
1005
1006 statement.bindText(1, manifestURL);
1007
1008 int result = statement.step();
1009 if (result == SQLResultDone)
1010 return false;
1011
1012 if (result != SQLResultRow) {
1013 LOG_ERROR("Could not get the size of the cache group, error \"%s\"", m_database.lastErrorMsg());
1014 return false;
1015 }
1016
1017 *size = statement.getColumnInt64(0);
1018 return true;
1019 }
1020
deleteCacheGroup(const String & manifestURL)1021 bool ApplicationCacheStorage::deleteCacheGroup(const String& manifestURL)
1022 {
1023 SQLiteTransaction deleteTransaction(m_database);
1024 // Check to see if the group is in memory.
1025 ApplicationCacheGroup* group = m_cachesInMemory.get(manifestURL);
1026 if (group)
1027 cacheGroupMadeObsolete(group);
1028 else {
1029 // The cache group is not in memory, so remove it from the disk.
1030 openDatabase(false);
1031 if (!m_database.isOpen())
1032 return false;
1033
1034 SQLiteStatement idStatement(m_database, "SELECT id FROM CacheGroups WHERE manifestURL=?");
1035 if (idStatement.prepare() != SQLResultOk)
1036 return false;
1037
1038 idStatement.bindText(1, manifestURL);
1039
1040 int result = idStatement.step();
1041 if (result == SQLResultDone)
1042 return false;
1043
1044 if (result != SQLResultRow) {
1045 LOG_ERROR("Could not load cache group id, error \"%s\"", m_database.lastErrorMsg());
1046 return false;
1047 }
1048
1049 int64_t groupId = idStatement.getColumnInt64(0);
1050
1051 SQLiteStatement cacheStatement(m_database, "DELETE FROM Caches WHERE cacheGroup=?");
1052 if (cacheStatement.prepare() != SQLResultOk)
1053 return false;
1054
1055 SQLiteStatement groupStatement(m_database, "DELETE FROM CacheGroups WHERE id=?");
1056 if (groupStatement.prepare() != SQLResultOk)
1057 return false;
1058
1059 cacheStatement.bindInt64(1, groupId);
1060 executeStatement(cacheStatement);
1061 groupStatement.bindInt64(1, groupId);
1062 executeStatement(groupStatement);
1063 }
1064
1065 deleteTransaction.commit();
1066 return true;
1067 }
1068
vacuumDatabaseFile()1069 void ApplicationCacheStorage::vacuumDatabaseFile()
1070 {
1071 openDatabase(false);
1072 if (!m_database.isOpen())
1073 return;
1074
1075 m_database.runVacuumCommand();
1076 }
1077
checkForMaxSizeReached()1078 void ApplicationCacheStorage::checkForMaxSizeReached()
1079 {
1080 if (m_database.lastError() == SQLResultFull)
1081 m_isMaximumSizeReached = true;
1082 }
1083
ApplicationCacheStorage()1084 ApplicationCacheStorage::ApplicationCacheStorage()
1085 : m_maximumSize(INT_MAX)
1086 , m_isMaximumSizeReached(false)
1087 {
1088 }
1089
cacheStorage()1090 ApplicationCacheStorage& cacheStorage()
1091 {
1092 DEFINE_STATIC_LOCAL(ApplicationCacheStorage, storage, ());
1093
1094 return storage;
1095 }
1096
1097 } // namespace WebCore
1098
1099 #endif // ENABLE(OFFLINE_WEB_APPLICATIONS)
1100