1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "storage/browser/quota/quota_database.h"
#include <vector>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_macros.h"
#include "sql/connection.h"
#include "sql/meta_table.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "storage/browser/quota/special_storage_policy.h"
namespace storage {
namespace {
// Definitions for database schema.
const int kCurrentVersion = 4;
const int kCompatibleVersion = 2;
const char kHostQuotaTable[] = "HostQuotaTable";
const char kOriginInfoTable[] = "OriginInfoTable";
const char kIsOriginTableBootstrapped[] = "IsOriginTableBootstrapped";
bool VerifyValidQuotaConfig(const char* key) {
return (key != NULL &&
(!strcmp(key, QuotaDatabase::kDesiredAvailableSpaceKey) ||
!strcmp(key, QuotaDatabase::kTemporaryQuotaOverrideKey)));
}
const int kCommitIntervalMs = 30000;
enum OriginType {
// This enum is logged to UMA so only append to it - don't change
// the meaning of the existing values.
OTHER = 0,
NONE = 1,
GOOGLE_DURABLE = 2,
NON_GOOGLE_DURABLE = 3,
GOOGLE_UNLIMITED_EXTENSION = 4,
NON_GOOGLE_UNLIMITED_EXTENSION = 5,
IN_USE = 6,
MAX_ORIGIN_TYPE
};
void HistogramOriginType(const OriginType& entry) {
UMA_HISTOGRAM_ENUMERATION("Quota.LRUOriginTypes", entry, MAX_ORIGIN_TYPE);
}
} // anonymous namespace
// static
const char QuotaDatabase::kDesiredAvailableSpaceKey[] = "DesiredAvailableSpace";
const char QuotaDatabase::kTemporaryQuotaOverrideKey[] =
"TemporaryQuotaOverride";
const QuotaDatabase::TableSchema QuotaDatabase::kTables[] = {
{ kHostQuotaTable,
"(host TEXT NOT NULL,"
" type INTEGER NOT NULL,"
" quota INTEGER DEFAULT 0,"
" UNIQUE(host, type))" },
{ kOriginInfoTable,
"(origin TEXT NOT NULL,"
" type INTEGER NOT NULL,"
" used_count INTEGER DEFAULT 0,"
" last_access_time INTEGER DEFAULT 0,"
" last_modified_time INTEGER DEFAULT 0,"
" UNIQUE(origin, type))" },
};
// static
const QuotaDatabase::IndexSchema QuotaDatabase::kIndexes[] = {
{ "HostIndex",
kHostQuotaTable,
"(host)",
false },
{ "OriginInfoIndex",
kOriginInfoTable,
"(origin)",
false },
{ "OriginLastAccessTimeIndex",
kOriginInfoTable,
"(last_access_time)",
false },
{ "OriginLastModifiedTimeIndex",
kOriginInfoTable,
"(last_modified_time)",
false },
};
struct QuotaDatabase::QuotaTableImporter {
bool Append(const QuotaTableEntry& entry) {
entries.push_back(entry);
return true;
}
std::vector<QuotaTableEntry> entries;
};
// Clang requires explicit out-of-line constructors for them.
QuotaDatabase::QuotaTableEntry::QuotaTableEntry()
: type(kStorageTypeUnknown),
quota(0) {
}
QuotaDatabase::QuotaTableEntry::QuotaTableEntry(
const std::string& host,
StorageType type,
int64 quota)
: host(host),
type(type),
quota(quota) {
}
QuotaDatabase::OriginInfoTableEntry::OriginInfoTableEntry()
: type(kStorageTypeUnknown),
used_count(0) {
}
QuotaDatabase::OriginInfoTableEntry::OriginInfoTableEntry(
const GURL& origin,
StorageType type,
int used_count,
const base::Time& last_access_time,
const base::Time& last_modified_time)
: origin(origin),
type(type),
used_count(used_count),
last_access_time(last_access_time),
last_modified_time(last_modified_time) {
}
// QuotaDatabase ------------------------------------------------------------
QuotaDatabase::QuotaDatabase(const base::FilePath& path)
: db_file_path_(path),
is_recreating_(false),
is_disabled_(false) {
}
QuotaDatabase::~QuotaDatabase() {
if (db_) {
db_->CommitTransaction();
}
}
void QuotaDatabase::CloseConnection() {
meta_table_.reset();
db_.reset();
}
bool QuotaDatabase::GetHostQuota(
const std::string& host, StorageType type, int64* quota) {
DCHECK(quota);
if (!LazyOpen(false))
return false;
const char* kSql =
"SELECT quota"
" FROM HostQuotaTable"
" WHERE host = ? AND type = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, host);
statement.BindInt(1, static_cast<int>(type));
if (!statement.Step())
return false;
*quota = statement.ColumnInt64(0);
return true;
}
bool QuotaDatabase::SetHostQuota(
const std::string& host, StorageType type, int64 quota) {
DCHECK_GE(quota, 0);
if (!LazyOpen(true))
return false;
const char* kSql =
"INSERT OR REPLACE INTO HostQuotaTable"
" (quota, host, type)"
" VALUES (?, ?, ?)";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, quota);
statement.BindString(1, host);
statement.BindInt(2, static_cast<int>(type));
if (!statement.Run())
return false;
ScheduleCommit();
return true;
}
bool QuotaDatabase::SetOriginLastAccessTime(
const GURL& origin, StorageType type, base::Time last_access_time) {
if (!LazyOpen(true))
return false;
sql::Statement statement;
int used_count = 1;
if (FindOriginUsedCount(origin, type, &used_count)) {
++used_count;
const char* kSql =
"UPDATE OriginInfoTable"
" SET used_count = ?, last_access_time = ?"
" WHERE origin = ? AND type = ?";
statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
} else {
const char* kSql =
"INSERT INTO OriginInfoTable"
" (used_count, last_access_time, origin, type)"
" VALUES (?, ?, ?, ?)";
statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
}
statement.BindInt(0, used_count);
statement.BindInt64(1, last_access_time.ToInternalValue());
statement.BindString(2, origin.spec());
statement.BindInt(3, static_cast<int>(type));
if (!statement.Run())
return false;
ScheduleCommit();
return true;
}
bool QuotaDatabase::SetOriginLastModifiedTime(
const GURL& origin, StorageType type, base::Time last_modified_time) {
if (!LazyOpen(true))
return false;
sql::Statement statement;
int dummy;
if (FindOriginUsedCount(origin, type, &dummy)) {
const char* kSql =
"UPDATE OriginInfoTable"
" SET last_modified_time = ?"
" WHERE origin = ? AND type = ?";
statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
} else {
const char* kSql =
"INSERT INTO OriginInfoTable"
" (last_modified_time, origin, type) VALUES (?, ?, ?)";
statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
}
statement.BindInt64(0, last_modified_time.ToInternalValue());
statement.BindString(1, origin.spec());
statement.BindInt(2, static_cast<int>(type));
if (!statement.Run())
return false;
ScheduleCommit();
return true;
}
bool QuotaDatabase::RegisterInitialOriginInfo(
const std::set<GURL>& origins, StorageType type) {
if (!LazyOpen(true))
return false;
typedef std::set<GURL>::const_iterator itr_type;
for (itr_type itr = origins.begin(), end = origins.end();
itr != end; ++itr) {
const char* kSql =
"INSERT OR IGNORE INTO OriginInfoTable"
" (origin, type) VALUES (?, ?)";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, itr->spec());
statement.BindInt(1, static_cast<int>(type));
if (!statement.Run())
return false;
}
ScheduleCommit();
return true;
}
bool QuotaDatabase::DeleteHostQuota(
const std::string& host, StorageType type) {
if (!LazyOpen(false))
return false;
const char* kSql =
"DELETE FROM HostQuotaTable"
" WHERE host = ? AND type = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, host);
statement.BindInt(1, static_cast<int>(type));
if (!statement.Run())
return false;
ScheduleCommit();
return true;
}
bool QuotaDatabase::DeleteOriginInfo(
const GURL& origin, StorageType type) {
if (!LazyOpen(false))
return false;
const char* kSql =
"DELETE FROM OriginInfoTable"
" WHERE origin = ? AND type = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, origin.spec());
statement.BindInt(1, static_cast<int>(type));
if (!statement.Run())
return false;
ScheduleCommit();
return true;
}
bool QuotaDatabase::GetQuotaConfigValue(const char* key, int64* value) {
if (!LazyOpen(false))
return false;
DCHECK(VerifyValidQuotaConfig(key));
return meta_table_->GetValue(key, value);
}
bool QuotaDatabase::SetQuotaConfigValue(const char* key, int64 value) {
if (!LazyOpen(true))
return false;
DCHECK(VerifyValidQuotaConfig(key));
return meta_table_->SetValue(key, value);
}
bool QuotaDatabase::GetLRUOrigin(
StorageType type,
const std::set<GURL>& exceptions,
SpecialStoragePolicy* special_storage_policy,
GURL* origin) {
DCHECK(origin);
if (!LazyOpen(false))
return false;
const char* kSql = "SELECT origin FROM OriginInfoTable"
" WHERE type = ?"
" ORDER BY last_access_time ASC";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt(0, static_cast<int>(type));
while (statement.Step()) {
GURL url(statement.ColumnString(0));
if (exceptions.find(url) != exceptions.end()) {
HistogramOriginType(IN_USE);
continue;
}
if (special_storage_policy) {
bool is_google = url.DomainIs("google.com");
if (special_storage_policy->IsStorageDurable(url)) {
HistogramOriginType(is_google ? GOOGLE_DURABLE : NON_GOOGLE_DURABLE);
continue;
}
if (special_storage_policy->IsStorageUnlimited(url)) {
HistogramOriginType(is_google ? GOOGLE_UNLIMITED_EXTENSION
: NON_GOOGLE_UNLIMITED_EXTENSION);
continue;
}
}
HistogramOriginType(OTHER);
*origin = url;
return true;
}
HistogramOriginType(NONE);
*origin = GURL();
return statement.Succeeded();
}
bool QuotaDatabase::GetOriginsModifiedSince(
StorageType type, std::set<GURL>* origins, base::Time modified_since) {
DCHECK(origins);
if (!LazyOpen(false))
return false;
const char* kSql = "SELECT origin FROM OriginInfoTable"
" WHERE type = ? AND last_modified_time >= ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt(0, static_cast<int>(type));
statement.BindInt64(1, modified_since.ToInternalValue());
origins->clear();
while (statement.Step())
origins->insert(GURL(statement.ColumnString(0)));
return statement.Succeeded();
}
bool QuotaDatabase::IsOriginDatabaseBootstrapped() {
if (!LazyOpen(true))
return false;
int flag = 0;
return meta_table_->GetValue(kIsOriginTableBootstrapped, &flag) && flag;
}
bool QuotaDatabase::SetOriginDatabaseBootstrapped(bool bootstrap_flag) {
if (!LazyOpen(true))
return false;
return meta_table_->SetValue(kIsOriginTableBootstrapped, bootstrap_flag);
}
void QuotaDatabase::Commit() {
if (!db_)
return;
if (timer_.IsRunning())
timer_.Stop();
db_->CommitTransaction();
db_->BeginTransaction();
}
void QuotaDatabase::ScheduleCommit() {
if (timer_.IsRunning())
return;
timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kCommitIntervalMs),
this, &QuotaDatabase::Commit);
}
bool QuotaDatabase::FindOriginUsedCount(
const GURL& origin, StorageType type, int* used_count) {
DCHECK(used_count);
if (!LazyOpen(false))
return false;
const char* kSql =
"SELECT used_count FROM OriginInfoTable"
" WHERE origin = ? AND type = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindString(0, origin.spec());
statement.BindInt(1, static_cast<int>(type));
if (!statement.Step())
return false;
*used_count = statement.ColumnInt(0);
return true;
}
bool QuotaDatabase::LazyOpen(bool create_if_needed) {
if (db_)
return true;
// If we tried and failed once, don't try again in the same session
// to avoid creating an incoherent mess on disk.
if (is_disabled_)
return false;
bool in_memory_only = db_file_path_.empty();
if (!create_if_needed &&
(in_memory_only || !base::PathExists(db_file_path_))) {
return false;
}
db_.reset(new sql::Connection);
meta_table_.reset(new sql::MetaTable);
db_->set_histogram_tag("Quota");
bool opened = false;
if (in_memory_only) {
opened = db_->OpenInMemory();
} else if (!base::CreateDirectory(db_file_path_.DirName())) {
LOG(ERROR) << "Failed to create quota database directory.";
} else {
opened = db_->Open(db_file_path_);
if (opened)
db_->Preload();
}
if (!opened || !EnsureDatabaseVersion()) {
LOG(ERROR) << "Could not open the quota database, resetting.";
if (!ResetSchema()) {
LOG(ERROR) << "Failed to reset the quota database.";
is_disabled_ = true;
db_.reset();
meta_table_.reset();
return false;
}
}
// Start a long-running transaction.
db_->BeginTransaction();
return true;
}
bool QuotaDatabase::EnsureDatabaseVersion() {
static const size_t kTableCount = arraysize(kTables);
static const size_t kIndexCount = arraysize(kIndexes);
if (!sql::MetaTable::DoesTableExist(db_.get()))
return CreateSchema(db_.get(), meta_table_.get(),
kCurrentVersion, kCompatibleVersion,
kTables, kTableCount,
kIndexes, kIndexCount);
if (!meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion))
return false;
if (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) {
LOG(WARNING) << "Quota database is too new.";
return false;
}
if (meta_table_->GetVersionNumber() < kCurrentVersion) {
if (!UpgradeSchema(meta_table_->GetVersionNumber()))
return ResetSchema();
}
#ifndef NDEBUG
DCHECK(sql::MetaTable::DoesTableExist(db_.get()));
for (size_t i = 0; i < kTableCount; ++i) {
DCHECK(db_->DoesTableExist(kTables[i].table_name));
}
#endif
return true;
}
// static
bool QuotaDatabase::CreateSchema(
sql::Connection* database,
sql::MetaTable* meta_table,
int schema_version, int compatible_version,
const TableSchema* tables, size_t tables_size,
const IndexSchema* indexes, size_t indexes_size) {
// TODO(kinuko): Factor out the common code to create databases.
sql::Transaction transaction(database);
if (!transaction.Begin())
return false;
if (!meta_table->Init(database, schema_version, compatible_version))
return false;
for (size_t i = 0; i < tables_size; ++i) {
std::string sql("CREATE TABLE ");
sql += tables[i].table_name;
sql += tables[i].columns;
if (!database->Execute(sql.c_str())) {
VLOG(1) << "Failed to execute " << sql;
return false;
}
}
for (size_t i = 0; i < indexes_size; ++i) {
std::string sql;
if (indexes[i].unique)
sql += "CREATE UNIQUE INDEX ";
else
sql += "CREATE INDEX ";
sql += indexes[i].index_name;
sql += " ON ";
sql += indexes[i].table_name;
sql += indexes[i].columns;
if (!database->Execute(sql.c_str())) {
VLOG(1) << "Failed to execute " << sql;
return false;
}
}
return transaction.Commit();
}
bool QuotaDatabase::ResetSchema() {
DCHECK(!db_file_path_.empty());
DCHECK(base::PathExists(db_file_path_));
VLOG(1) << "Deleting existing quota data and starting over.";
db_.reset();
meta_table_.reset();
if (!sql::Connection::Delete(db_file_path_))
return false;
// So we can't go recursive.
if (is_recreating_)
return false;
base::AutoReset<bool> auto_reset(&is_recreating_, true);
return LazyOpen(true);
}
bool QuotaDatabase::UpgradeSchema(int current_version) {
if (current_version == 2) {
QuotaTableImporter importer;
typedef std::vector<QuotaTableEntry> QuotaTableEntries;
if (!DumpQuotaTable(base::Bind(&QuotaTableImporter::Append,
base::Unretained(&importer)))) {
return false;
}
ResetSchema();
for (QuotaTableEntries::const_iterator iter = importer.entries.begin();
iter != importer.entries.end(); ++iter) {
if (!SetHostQuota(iter->host, iter->type, iter->quota))
return false;
}
Commit();
return true;
}
return false;
}
bool QuotaDatabase::DumpQuotaTable(const QuotaTableCallback& callback) {
if (!LazyOpen(true))
return false;
const char* kSql = "SELECT * FROM HostQuotaTable";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
while (statement.Step()) {
QuotaTableEntry entry = QuotaTableEntry(
statement.ColumnString(0),
static_cast<StorageType>(statement.ColumnInt(1)),
statement.ColumnInt64(2));
if (!callback.Run(entry))
return true;
}
return statement.Succeeded();
}
bool QuotaDatabase::DumpOriginInfoTable(
const OriginInfoTableCallback& callback) {
if (!LazyOpen(true))
return false;
const char* kSql = "SELECT * FROM OriginInfoTable";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
while (statement.Step()) {
OriginInfoTableEntry entry(
GURL(statement.ColumnString(0)),
static_cast<StorageType>(statement.ColumnInt(1)),
statement.ColumnInt(2),
base::Time::FromInternalValue(statement.ColumnInt64(3)),
base::Time::FromInternalValue(statement.ColumnInt64(4)));
if (!callback.Run(entry))
return true;
}
return statement.Succeeded();
}
bool operator<(const QuotaDatabase::QuotaTableEntry& lhs,
const QuotaDatabase::QuotaTableEntry& rhs) {
if (lhs.host < rhs.host) return true;
if (rhs.host < lhs.host) return false;
if (lhs.type < rhs.type) return true;
if (rhs.type < lhs.type) return false;
return lhs.quota < rhs.quota;
}
bool operator<(const QuotaDatabase::OriginInfoTableEntry& lhs,
const QuotaDatabase::OriginInfoTableEntry& rhs) {
if (lhs.origin < rhs.origin) return true;
if (rhs.origin < lhs.origin) return false;
if (lhs.type < rhs.type) return true;
if (rhs.type < lhs.type) return false;
if (lhs.used_count < rhs.used_count) return true;
if (rhs.used_count < lhs.used_count) return false;
return lhs.last_access_time < rhs.last_access_time;
}
} // namespace storage
|