#include "net/extras/sqlite/sqlite_persistent_cookie_store.h"
#include <iterator>
#include <map>
#include <memory>
#include <set>
#include <tuple>
#include <unordered_set>
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/task/sequenced_task_runner.h"
#include "base/thread_annotations.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_constants.h"
#include "net/cookies/cookie_util.h"
#include "net/extras/sqlite/cookie_crypto_delegate.h"
#include "net/extras/sqlite/sqlite_persistent_store_backend_base.h"
#include "net/log/net_log.h"
#include "net/log/net_log_values.h"
#include "sql/error_delegate_util.h"
#include "sql/meta_table.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"
#include "url/third_party/mozilla/url_parse.h"
using base::Time;
namespace {
base::Value::Dict CookieKeyedLoadNetLogParams(
const std::string& key,
net::NetLogCaptureMode capture_mode) {
if (!net::NetLogCaptureIncludesSensitive(capture_mode))
return base::Value::Dict();
base::Value::Dict dict;
dict.Set("key", key);
return dict;
}
enum CookieLoadProblem {
COOKIE_LOAD_PROBLEM_DECRYPT_FAILED = 0,
COOKIE_LOAD_PROBLEM_NON_CANONICAL = 2,
COOKIE_LOAD_PROBLEM_OPEN_DB = 3,
COOKIE_LOAD_PROBLEM_RECOVERY_FAILED = 4,
COOKIE_LOAD_DELETE_COOKIE_PARTITION_FAILED = 5,
COOKIE_LOAD_PROBLEM_LAST_ENTRY
};
enum CookieCommitProblem {
COOKIE_COMMIT_PROBLEM_ENCRYPT_FAILED = 0,
COOKIE_COMMIT_PROBLEM_ADD = 1,
COOKIE_COMMIT_PROBLEM_UPDATE_ACCESS = 2,
COOKIE_COMMIT_PROBLEM_DELETE = 3,
COOKIE_COMMIT_PROBLEM_TRANSACTION_COMMIT = 4,
COOKIE_COMMIT_PROBLEM_LAST_ENTRY
};
void RecordCookieLoadProblem(CookieLoadProblem event) {
UMA_HISTOGRAM_ENUMERATION("Cookie.LoadProblem", event,
COOKIE_LOAD_PROBLEM_LAST_ENTRY);
}
void RecordCookieCommitProblem(CookieCommitProblem event) {
UMA_HISTOGRAM_ENUMERATION("Cookie.CommitProblem", event,
COOKIE_COMMIT_PROBLEM_LAST_ENTRY);
}
#if BUILDFLAG(IS_IOS)
const int kLoadDelayMilliseconds = 0;
#else
const int kLoadDelayMilliseconds = 0;
#endif
}
namespace net {
base::TaskPriority GetCookieStoreBackgroundSequencePriority() {
return base::TaskPriority::USER_BLOCKING;
}
namespace {
const int kCurrentVersionNumber = 18;
const int kCompatibleVersionNumber = 18;
}
class SQLitePersistentCookieStore::Backend
: public SQLitePersistentStoreBackendBase {
public:
Backend(const base::FilePath& path,
scoped_refptr<base::SequencedTaskRunner> client_task_runner,
scoped_refptr<base::SequencedTaskRunner> background_task_runner,
bool restore_old_session_cookies,
CookieCryptoDelegate* crypto_delegate,
bool enable_exclusive_access)
: SQLitePersistentStoreBackendBase(path,
"Cookie",
kCurrentVersionNumber,
kCompatibleVersionNumber,
std::move(background_task_runner),
std::move(client_task_runner),
enable_exclusive_access),
restore_old_session_cookies_(restore_old_session_cookies),
crypto_(crypto_delegate) {}
Backend(const Backend&) = delete;
Backend& operator=(const Backend&) = delete;
void Load(LoadedCallback loaded_callback);
void LoadCookiesForKey(const std::string& domain,
LoadedCallback loaded_callback);
bool MakeCookiesFromSQLStatement(
std::vector<std::unique_ptr<CanonicalCookie>>& cookies,
sql::Statement& statement,
std::unordered_set<std::string>& top_frame_site_keys_to_delete);
void AddCookie(const CanonicalCookie& cc);
void UpdateCookieAccessTime(const CanonicalCookie& cc);
void DeleteCookie(const CanonicalCookie& cc);
size_t GetQueueLengthForTesting();
void DeleteAllInList(const std::list<CookieOrigin>& cookies);
private:
~Backend() override {
DCHECK_EQ(0u, num_pending_);
DCHECK(pending_.empty());
}
absl::optional<int> DoMigrateDatabaseSchema() override;
class PendingOperation {
public:
enum OperationType {
COOKIE_ADD,
COOKIE_UPDATEACCESS,
COOKIE_DELETE,
};
PendingOperation(OperationType op, const CanonicalCookie& cc)
: op_(op), cc_(cc) {}
OperationType op() const { return op_; }
const CanonicalCookie& cc() const { return cc_; }
private:
OperationType op_;
CanonicalCookie cc_;
};
private:
void LoadAndNotifyInBackground(LoadedCallback loaded_callback);
void LoadKeyAndNotifyInBackground(const std::string& domains,
LoadedCallback loaded_callback);
void Notify(LoadedCallback loaded_callback, bool load_success);
void CompleteLoadInForeground(LoadedCallback loaded_callback,
bool load_success);
void CompleteLoadForKeyInForeground(LoadedCallback loaded_callback,
bool load_success);
bool CreateDatabaseSchema() override;
bool DoInitializeDatabase() override;
void ChainLoadCookies(LoadedCallback loaded_callback);
bool LoadCookiesForDomains(const std::set<std::string>& key);
void DeleteTopFrameSiteKeys(
const std::unordered_set<std::string>& top_frame_site_keys);
void BatchOperation(PendingOperation::OperationType op,
const CanonicalCookie& cc);
void DoCommit() override;
void DeleteSessionCookiesOnStartup();
void BackgroundDeleteAllInList(const std::list<CookieOrigin>& cookies);
void FinishedLoadingCookies(LoadedCallback loaded_callback, bool success);
void RecordOpenDBProblem() override {
RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_OPEN_DB);
}
void RecordDBMigrationProblem() override {
RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_OPEN_DB);
}
typedef std::list<std::unique_ptr<PendingOperation>> PendingOperationsForKey;
typedef std::map<CanonicalCookie::UniqueCookieKey, PendingOperationsForKey>
PendingOperationsMap;
PendingOperationsMap pending_ GUARDED_BY(lock_);
PendingOperationsMap::size_type num_pending_ GUARDED_BY(lock_) = 0;
base::Lock lock_;
std::vector<std::unique_ptr<CanonicalCookie>> cookies_ GUARDED_BY(lock_);
std::map<std::string, std::set<std::string>> keys_to_load_;
bool restore_old_session_cookies_;
base::TimeDelta cookie_load_duration_;
base::Lock metrics_lock_;
int num_priority_waiting_ GUARDED_BY(metrics_lock_) = 0;
int total_priority_requests_ GUARDED_BY(metrics_lock_) = 0;
base::Time current_priority_wait_start_ GUARDED_BY(metrics_lock_);
base::TimeDelta priority_wait_duration_ GUARDED_BY(metrics_lock_);
raw_ptr<CookieCryptoDelegate, DanglingUntriaged> crypto_;
};
namespace {
enum DBCookiePriority {
kCookiePriorityLow = 0,
kCookiePriorityMedium = 1,
kCookiePriorityHigh = 2,
};
DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
switch (value) {
case COOKIE_PRIORITY_LOW:
return kCookiePriorityLow;
case COOKIE_PRIORITY_MEDIUM:
return kCookiePriorityMedium;
case COOKIE_PRIORITY_HIGH:
return kCookiePriorityHigh;
}
NOTREACHED();
return kCookiePriorityMedium;
}
CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
switch (value) {
case kCookiePriorityLow:
return COOKIE_PRIORITY_LOW;
case kCookiePriorityMedium:
return COOKIE_PRIORITY_MEDIUM;
case kCookiePriorityHigh:
return COOKIE_PRIORITY_HIGH;
}
NOTREACHED();
return COOKIE_PRIORITY_DEFAULT;
}
enum DBCookieSameSite {
kCookieSameSiteUnspecified = -1,
kCookieSameSiteNoRestriction = 0,
kCookieSameSiteLax = 1,
kCookieSameSiteStrict = 2,
kCookieSameSiteExtended = 3
};
DBCookieSameSite CookieSameSiteToDBCookieSameSite(CookieSameSite value) {
switch (value) {
case CookieSameSite::NO_RESTRICTION:
return kCookieSameSiteNoRestriction;
case CookieSameSite::LAX_MODE:
return kCookieSameSiteLax;
case CookieSameSite::STRICT_MODE:
return kCookieSameSiteStrict;
case CookieSameSite::UNSPECIFIED:
return kCookieSameSiteUnspecified;
}
}
CookieSameSite DBCookieSameSiteToCookieSameSite(DBCookieSameSite value) {
CookieSameSite samesite = CookieSameSite::UNSPECIFIED;
switch (value) {
case kCookieSameSiteNoRestriction:
samesite = CookieSameSite::NO_RESTRICTION;
break;
case kCookieSameSiteLax:
samesite = CookieSameSite::LAX_MODE;
break;
case kCookieSameSiteStrict:
samesite = CookieSameSite::STRICT_MODE;
break;
case kCookieSameSiteExtended:
case kCookieSameSiteUnspecified:
samesite = CookieSameSite::UNSPECIFIED;
break;
}
return samesite;
}
CookieSourceScheme DBToCookieSourceScheme(int value) {
int enum_max_value = static_cast<int>(CookieSourceScheme::kMaxValue);
if (value < 0 || value > enum_max_value) {
DLOG(WARNING) << "DB read of cookie's source scheme is invalid. Resetting "
"value to unset.";
value = static_cast<int>(
CookieSourceScheme::kUnset);
}
return static_cast<CookieSourceScheme>(value);
}
class IncrementTimeDelta {
public:
explicit IncrementTimeDelta(base::TimeDelta* delta)
: delta_(delta), original_value_(*delta), start_(base::Time::Now()) {}
IncrementTimeDelta(const IncrementTimeDelta&) = delete;
IncrementTimeDelta& operator=(const IncrementTimeDelta&) = delete;
~IncrementTimeDelta() {
*delta_ = original_value_ + base::Time::Now() - start_;
}
private:
raw_ptr<base::TimeDelta> delta_;
base::TimeDelta original_value_;
base::Time start_;
};
bool CreateV10Schema(sql::Database* db) {
DCHECK(!db->DoesTableExist("cookies"));
std::string stmt(base::StringPrintf(
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL DEFAULT 1,"
"is_persistent INTEGER NOT NULL DEFAULT 1,"
"priority INTEGER NOT NULL DEFAULT %d,"
"encrypted_value BLOB DEFAULT '',"
"firstpartyonly INTEGER NOT NULL DEFAULT %d,"
"UNIQUE (host_key, name, path))",
CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT),
CookieSameSiteToDBCookieSameSite(CookieSameSite::NO_RESTRICTION)));
if (!db->Execute(stmt.c_str()))
return false;
return true;
}
bool CreateV11Schema(sql::Database* db) {
DCHECK(!db->DoesTableExist("cookies"));
std::string stmt(base::StringPrintf(
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL DEFAULT 1,"
"is_persistent INTEGER NOT NULL DEFAULT 1,"
"priority INTEGER NOT NULL DEFAULT %d,"
"encrypted_value BLOB DEFAULT '',"
"samesite INTEGER NOT NULL DEFAULT %d,"
"UNIQUE (host_key, name, path))",
CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT),
CookieSameSiteToDBCookieSameSite(CookieSameSite::UNSPECIFIED)));
if (!db->Execute(stmt.c_str()))
return false;
return true;
}
bool CreateV15Schema(sql::Database* db) {
DCHECK(!db->DoesTableExist("cookies"));
std::string stmt(base::StringPrintf(
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"host_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB DEFAULT '',"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL DEFAULT 1,"
"is_persistent INTEGER NOT NULL DEFAULT 1,"
"priority INTEGER NOT NULL DEFAULT %d,"
"samesite INTEGER NOT NULL DEFAULT %d,"
"source_scheme INTEGER NOT NULL DEFAULT %d,"
"source_port INTEGER NOT NULL DEFAULT %d,"
"is_same_party INTEGER NOT NULL DEFAULT 0,"
"UNIQUE (top_frame_site_key, host_key, name, path))",
CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT),
CookieSameSiteToDBCookieSameSite(CookieSameSite::UNSPECIFIED),
static_cast<int>(CookieSourceScheme::kUnset),
SQLitePersistentCookieStore::kDefaultUnknownPort));
if (!db->Execute(stmt.c_str()))
return false;
return true;
}
bool CreateV16Schema(sql::Database* db) {
DCHECK(!db->DoesTableExist("cookies"));
const char* kCreateTableQuery =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"is_same_party INTEGER NOT NULL);";
const char* kCreateIndexQuery =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, name, path)";
if (!db->Execute(kCreateTableQuery))
return false;
if (!db->Execute(kCreateIndexQuery))
return false;
return true;
}
bool CreateV17Schema(sql::Database* db) {
return CreateV16Schema(db);
}
bool CreateV18Schema(sql::Database* db) {
DCHECK(!db->DoesTableExist("cookies"));
const char* kCreateTableQuery =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"is_same_party INTEGER NOT NULL,"
"last_update_utc INTEGER NOT NULL);";
const char* kCreateIndexQuery =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, name, path)";
if (!db->Execute(kCreateTableQuery))
return false;
if (!db->Execute(kCreateIndexQuery))
return false;
return true;
}
}
void SQLitePersistentCookieStore::Backend::Load(
LoadedCallback loaded_callback) {
PostBackgroundTask(FROM_HERE,
base::BindOnce(&Backend::LoadAndNotifyInBackground, this,
std::move(loaded_callback)));
}
void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
const std::string& key,
LoadedCallback loaded_callback) {
{
base::AutoLock locked(metrics_lock_);
if (num_priority_waiting_ == 0)
current_priority_wait_start_ = base::Time::Now();
num_priority_waiting_++;
total_priority_requests_++;
}
PostBackgroundTask(
FROM_HERE, base::BindOnce(&Backend::LoadKeyAndNotifyInBackground, this,
key, std::move(loaded_callback)));
}
void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
LoadedCallback loaded_callback) {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
IncrementTimeDelta increment(&cookie_load_duration_);
if (!InitializeDatabase()) {
PostClientTask(FROM_HERE,
base::BindOnce(&Backend::CompleteLoadInForeground, this,
std::move(loaded_callback), false));
} else {
ChainLoadCookies(std::move(loaded_callback));
}
}
void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
const std::string& key,
LoadedCallback loaded_callback) {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
IncrementTimeDelta increment(&cookie_load_duration_);
bool success = false;
if (InitializeDatabase()) {
auto it = keys_to_load_.find(key);
if (it != keys_to_load_.end()) {
success = LoadCookiesForDomains(it->second);
keys_to_load_.erase(it);
} else {
success = true;
}
}
PostClientTask(
FROM_HERE,
base::BindOnce(
&SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
this, std::move(loaded_callback), success));
}
void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
LoadedCallback loaded_callback,
bool load_success) {
DCHECK(client_task_runner()->RunsTasksInCurrentSequence());
Notify(std::move(loaded_callback), load_success);
{
base::AutoLock locked(metrics_lock_);
num_priority_waiting_--;
if (num_priority_waiting_ == 0) {
priority_wait_duration_ +=
base::Time::Now() - current_priority_wait_start_;
}
}
}
void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
LoadedCallback loaded_callback,
bool load_success) {
Notify(std::move(loaded_callback), load_success);
}
void SQLitePersistentCookieStore::Backend::Notify(
LoadedCallback loaded_callback,
bool load_success) {
DCHECK(client_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<CanonicalCookie>> cookies;
{
base::AutoLock locked(lock_);
cookies.swap(cookies_);
}
std::move(loaded_callback).Run(std::move(cookies));
}
bool SQLitePersistentCookieStore::Backend::CreateDatabaseSchema() {
DCHECK(db());
if (db()->DoesTableExist("cookies"))
return true;
return CreateV18Schema(db());
}
bool SQLitePersistentCookieStore::Backend::DoInitializeDatabase() {
DCHECK(db());
sql::Statement smt(
db()->GetUniqueStatement("SELECT DISTINCT host_key FROM cookies"));
if (!smt.is_valid()) {
Reset();
return false;
}
std::vector<std::string> host_keys;
while (smt.Step())
host_keys.push_back(smt.ColumnString(0));
for (const auto& domain : host_keys) {
std::string key = CookieMonster::GetKey(domain);
keys_to_load_[key].insert(domain);
}
if (!restore_old_session_cookies_)
DeleteSessionCookiesOnStartup();
return true;
}
void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
LoadedCallback loaded_callback) {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
IncrementTimeDelta increment(&cookie_load_duration_);
bool load_success = true;
if (!db()) {
load_success = false;
} else if (keys_to_load_.size() > 0) {
auto it = keys_to_load_.begin();
load_success = LoadCookiesForDomains(it->second);
keys_to_load_.erase(it);
}
if (load_success && keys_to_load_.size() > 0) {
bool success = background_task_runner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&Backend::ChainLoadCookies, this,
std::move(loaded_callback)),
base::Milliseconds(kLoadDelayMilliseconds));
if (!success) {
LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
<< " to background_task_runner().";
}
} else {
FinishedLoadingCookies(std::move(loaded_callback), load_success);
}
}
bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
const std::set<std::string>& domains) {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
sql::Statement smt, delete_statement;
if (restore_old_session_cookies_) {
smt.Assign(db()->GetCachedStatement(
SQL_FROM_HERE,
"SELECT creation_utc, host_key, top_frame_site_key, name, value, path, "
"expires_utc, is_secure, is_httponly, last_access_utc, has_expires, "
"is_persistent, priority, encrypted_value, samesite, source_scheme, "
"source_port, is_same_party, last_update_utc FROM cookies WHERE "
"host_key = ?"));
} else {
smt.Assign(db()->GetCachedStatement(
SQL_FROM_HERE,
"SELECT creation_utc, host_key, top_frame_site_key, name, value, path, "
"expires_utc, is_secure, is_httponly, last_access_utc, has_expires, "
"is_persistent, priority, encrypted_value, samesite, source_scheme, "
"source_port, is_same_party, last_update_utc FROM cookies WHERE "
"host_key = ? AND "
"is_persistent = 1"));
}
delete_statement.Assign(db()->GetCachedStatement(
SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key = ?"));
if (!smt.is_valid() || !delete_statement.is_valid()) {
delete_statement.Clear();
smt.Clear();
Reset();
return false;
}
std::vector<std::unique_ptr<CanonicalCookie>> cookies;
std::unordered_set<std::string> top_frame_site_keys_to_delete;
auto it = domains.begin();
bool ok = true;
for (; it != domains.end() && ok; ++it) {
smt.BindString(0, *it);
ok = MakeCookiesFromSQLStatement(cookies, smt,
top_frame_site_keys_to_delete);
smt.Reset(true);
}
DeleteTopFrameSiteKeys(std::move(top_frame_site_keys_to_delete));
if (ok) {
base::AutoLock locked(lock_);
std::move(cookies.begin(), cookies.end(), std::back_inserter(cookies_));
} else {
for (const std::string& domain : domains) {
delete_statement.BindString(0, domain);
if (!delete_statement.Run()) {
RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_RECOVERY_FAILED);
}
delete_statement.Reset(true);
}
}
return true;
}
void SQLitePersistentCookieStore::Backend::DeleteTopFrameSiteKeys(
const std::unordered_set<std::string>& top_frame_site_keys) {
if (top_frame_site_keys.empty())
return;
sql::Statement delete_statement;
delete_statement.Assign(db()->GetCachedStatement(
SQL_FROM_HERE, "DELETE FROM cookies WHERE top_frame_site_key = ?"));
if (!delete_statement.is_valid())
return;
for (const std::string& key : top_frame_site_keys) {
delete_statement.BindString(0, key);
if (!delete_statement.Run())
RecordCookieLoadProblem(COOKIE_LOAD_DELETE_COOKIE_PARTITION_FAILED);
delete_statement.Reset(true);
}
}
bool SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
std::vector<std::unique_ptr<CanonicalCookie>>& cookies,
sql::Statement& statement,
std::unordered_set<std::string>& top_frame_site_keys_to_delete) {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
bool ok = true;
while (statement.Step()) {
std::string value;
std::string encrypted_value = statement.ColumnString(13);
if (!encrypted_value.empty() && crypto_) {
bool decrypt_ok = crypto_->DecryptString(encrypted_value, &value);
if (!decrypt_ok) {
RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_DECRYPT_FAILED);
ok = false;
continue;
}
} else {
value = statement.ColumnString(4);
}
absl::optional<CookiePartitionKey> cookie_partition_key;
std::string top_frame_site_key = statement.ColumnString(2);
if (!CookiePartitionKey::Deserialize(top_frame_site_key,
cookie_partition_key)) {
top_frame_site_keys_to_delete.insert(std::move(top_frame_site_key));
continue;
}
std::unique_ptr<net::CanonicalCookie> cc = CanonicalCookie::FromStorage(
statement.ColumnString(3),
value,
statement.ColumnString(1),
statement.ColumnString(5),
statement.ColumnTime(0),
statement.ColumnTime(6),
statement.ColumnTime(9),
statement.ColumnTime(18),
statement.ColumnBool(7),
statement.ColumnBool(8),
DBCookieSameSiteToCookieSameSite(static_cast<DBCookieSameSite>(
statement.ColumnInt(14))),
DBCookiePriorityToCookiePriority(static_cast<DBCookiePriority>(
statement.ColumnInt(12))),
statement.ColumnBool(17),
std::move(cookie_partition_key),
DBToCookieSourceScheme(statement.ColumnInt(15)),
statement.ColumnInt(16));
if (cc) {
DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
<< "CreationDate too recent";
if (!cc->LastUpdateDate().is_null()) {
DLOG_IF(WARNING, cc->LastUpdateDate() > Time::Now())
<< "LastUpdateDate too recent";
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Cookie.DaysSinceRefreshForRetrieval",
(base::Time::Now() - cc->LastUpdateDate()).InDays(), 1, 400, 100);
}
cookies.push_back(std::move(cc));
} else {
RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_NON_CANONICAL);
ok = false;
}
}
return ok;
}
absl::optional<int>
SQLitePersistentCookieStore::Backend::DoMigrateDatabaseSchema() {
int cur_version = meta_table()->GetVersionNumber();
if (cur_version == 9) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
return absl::nullopt;
if (!db()->Execute("DROP INDEX IF EXISTS domain"))
return absl::nullopt;
if (!db()->Execute("DROP INDEX IF EXISTS is_transient"))
return absl::nullopt;
if (!CreateV10Schema(db())) {
return absl::nullopt;
}
if (!db()->Execute(
"INSERT OR REPLACE INTO cookies "
"(creation_utc, host_key, name, value, path, expires_utc, "
"is_secure, is_httponly, last_access_utc, has_expires, "
"is_persistent, priority, encrypted_value, firstpartyonly) "
"SELECT creation_utc, host_key, name, value, path, expires_utc, "
" secure, httponly, last_access_utc, has_expires, "
" persistent, priority, encrypted_value, firstpartyonly "
"FROM cookies_old ORDER BY creation_utc ASC")) {
return absl::nullopt;
}
if (!db()->Execute("DROP TABLE cookies_old"))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 10) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
if (!db()->Execute("DROP TABLE IF EXISTS cookies_old; "
"ALTER TABLE cookies RENAME TO cookies_old"))
return absl::nullopt;
if (!CreateV11Schema(db()))
return absl::nullopt;
if (!db()->Execute(
"INSERT INTO cookies "
"(creation_utc, host_key, name, value, path, expires_utc, "
"is_secure, is_httponly, last_access_utc, has_expires, "
"is_persistent, priority, encrypted_value, samesite) "
"SELECT creation_utc, host_key, name, value, path, expires_utc, "
" is_secure, is_httponly, last_access_utc, has_expires, "
" is_persistent, priority, encrypted_value, firstpartyonly "
"FROM cookies_old")) {
return absl::nullopt;
}
if (!db()->Execute("DROP TABLE cookies_old"))
return absl::nullopt;
std::string update_stmt(base::StringPrintf(
"UPDATE cookies SET samesite=%d WHERE samesite=%d",
CookieSameSiteToDBCookieSameSite(CookieSameSite::UNSPECIFIED),
CookieSameSiteToDBCookieSameSite(CookieSameSite::NO_RESTRICTION)));
if (!db()->Execute(update_stmt.c_str()))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 11) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
std::string update_stmt(
base::StringPrintf("ALTER TABLE cookies ADD COLUMN source_scheme "
"INTEGER NOT NULL DEFAULT %d;",
static_cast<int>(CookieSourceScheme::kUnset)));
if (!db()->Execute(update_stmt.c_str()))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 12) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
std::string update_stmt(
base::StringPrintf("ALTER TABLE cookies ADD COLUMN source_port "
"INTEGER NOT NULL DEFAULT %d;"
"ALTER TABLE cookies ADD COLUMN is_same_party "
"INTEGER NOT NULL DEFAULT 0;",
kDefaultUnknownPort));
if (!db()->Execute(update_stmt.c_str()))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 13) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
#if BUILDFLAG(IS_WIN)
if (crypto_ && crypto_->ShouldEncrypt()) {
sql::Statement select_statement, update_statement;
select_statement.Assign(
db()->GetCachedStatement(SQL_FROM_HERE,
"SELECT rowid, encrypted_value "
"FROM cookies WHERE encrypted_value != ''"));
update_statement.Assign(
db()->GetCachedStatement(SQL_FROM_HERE,
"UPDATE cookies SET encrypted_value=? WHERE "
"rowid=?"));
if (!select_statement.is_valid() || !update_statement.is_valid())
return absl::nullopt;
std::map<int64_t, std::string> encrypted_values;
while (select_statement.Step()) {
int64_t rowid = select_statement.ColumnInt64(0);
std::string encrypted_value = select_statement.ColumnString(1);
DCHECK(!encrypted_value.empty());
std::string decrypted_value;
if (!crypto_->DecryptString(encrypted_value, &decrypted_value)) {
RecordCookieLoadProblem(COOKIE_LOAD_PROBLEM_DECRYPT_FAILED);
continue;
}
std::string new_encrypted_value;
if (!crypto_->EncryptString(decrypted_value, &new_encrypted_value)) {
RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_ENCRYPT_FAILED);
continue;
}
encrypted_values[rowid] = new_encrypted_value;
}
for (const auto& entry : encrypted_values) {
update_statement.Reset(true);
update_statement.BindString(0, entry.second);
update_statement.BindInt64(1, entry.first);
if (!update_statement.Run())
return absl::nullopt;
}
}
#endif
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 14) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
return absl::nullopt;
if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
return absl::nullopt;
if (!CreateV15Schema(db()))
return absl::nullopt;
std::string insert_cookies_sql = base::StringPrintf(
"INSERT OR REPLACE INTO cookies "
"(creation_utc, top_frame_site_key, host_key, name, value, "
" encrypted_value, path, expires_utc, is_secure, is_httponly, "
" last_access_utc, has_expires, is_persistent, priority, samesite, "
" source_scheme, source_port, is_same_party) "
"SELECT creation_utc, '%s', host_key, name, value, encrypted_value, "
" path, expires_utc, is_secure, is_httponly, last_access_utc, "
" has_expires, is_persistent, priority, samesite, source_scheme, "
" source_port, is_same_party "
"FROM cookies_old ORDER BY creation_utc ASC",
net::kEmptyCookiePartitionKey);
if (!db()->Execute(insert_cookies_sql.c_str()))
return absl::nullopt;
if (!db()->Execute("DROP TABLE cookies_old"))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 15) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
return absl::nullopt;
if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
return absl::nullopt;
if (!CreateV15Schema(db()))
return absl::nullopt;
std::string insert_cookies_sql = base::StringPrintf(
"INSERT OR REPLACE INTO cookies "
"(creation_utc, host_key, top_frame_site_key, name, value, "
"encrypted_value, path, expires_utc, is_secure, is_httponly, "
"last_access_utc, has_expires, is_persistent, priority, samesite, "
"source_scheme, source_port, is_same_party) "
"SELECT creation_utc, host_key, top_frame_site_key, name, value,"
" encrypted_value, path, expires_utc, is_secure, is_httponly,"
" last_access_utc, has_expires, is_persistent, priority, "
"samesite,"
" source_scheme, source_port, is_same_party "
"FROM cookies_old ORDER BY creation_utc ASC");
if (!db()->Execute(insert_cookies_sql.c_str()))
return absl::nullopt;
if (!db()->Execute("DROP TABLE cookies_old"))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 16) {
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
return absl::nullopt;
if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
return absl::nullopt;
if (!db()->Execute("DROP INDEX IF EXISTS cookies_unique_index"))
return absl::nullopt;
if (!CreateV17Schema(db()))
return absl::nullopt;
static constexpr char insert_cookies_sql[] =
"INSERT OR REPLACE INTO cookies "
"(creation_utc, host_key, top_frame_site_key, name, value, "
"encrypted_value, path, expires_utc, is_secure, is_httponly, "
"last_access_utc, has_expires, is_persistent, priority, samesite, "
"source_scheme, source_port, is_same_party) "
"SELECT creation_utc, host_key, top_frame_site_key, name, value,"
" encrypted_value, path, expires_utc, is_secure, is_httponly,"
" last_access_utc, has_expires, is_persistent, priority, "
"samesite,"
" source_scheme, source_port, is_same_party "
"FROM cookies_old ORDER BY creation_utc ASC";
if (!db()->Execute(insert_cookies_sql))
return absl::nullopt;
if (!db()->Execute("DROP TABLE cookies_old"))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
if (cur_version == 17) {
SCOPED_UMA_HISTOGRAM_TIMER("Cookie.TimeDatabaseMigrationToV18");
sql::Transaction transaction(db());
if (!transaction.Begin())
return absl::nullopt;
if (!db()->Execute("DROP TABLE IF EXISTS cookies_old"))
return absl::nullopt;
if (!db()->Execute("ALTER TABLE cookies RENAME TO cookies_old"))
return absl::nullopt;
if (!db()->Execute("DROP INDEX IF EXISTS cookies_unique_index"))
return absl::nullopt;
if (!CreateV18Schema(db()))
return absl::nullopt;
static constexpr char insert_cookies_sql[] =
"INSERT OR REPLACE INTO cookies "
"(creation_utc, host_key, top_frame_site_key, name, value, "
"encrypted_value, path, expires_utc, is_secure, is_httponly, "
"last_access_utc, has_expires, is_persistent, priority, samesite, "
"source_scheme, source_port, is_same_party, last_update_utc) "
"SELECT creation_utc, host_key, top_frame_site_key, name, value,"
" encrypted_value, path, expires_utc, is_secure, is_httponly,"
" last_access_utc, has_expires, is_persistent, priority, "
" samesite, source_scheme, source_port, is_same_party, 0 "
"FROM cookies_old ORDER BY creation_utc ASC";
if (!db()->Execute(insert_cookies_sql))
return absl::nullopt;
if (!db()->Execute("DROP TABLE cookies_old"))
return absl::nullopt;
++cur_version;
if (!meta_table()->SetVersionNumber(cur_version) ||
!meta_table()->SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber)) ||
!transaction.Commit()) {
return absl::nullopt;
}
}
return absl::make_optional(cur_version);
}
void SQLitePersistentCookieStore::Backend::AddCookie(
const CanonicalCookie& cc) {
BatchOperation(PendingOperation::COOKIE_ADD, cc);
}
void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
const CanonicalCookie& cc) {
BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
}
void SQLitePersistentCookieStore::Backend::DeleteCookie(
const CanonicalCookie& cc) {
BatchOperation(PendingOperation::COOKIE_DELETE, cc);
}
void SQLitePersistentCookieStore::Backend::BatchOperation(
PendingOperation::OperationType op,
const CanonicalCookie& cc) {
static const int kCommitIntervalMs = 30 * 1000;
static const size_t kCommitAfterBatchSize = 512;
DCHECK(!background_task_runner()->RunsTasksInCurrentSequence());
auto po = std::make_unique<PendingOperation>(op, cc);
PendingOperationsMap::size_type num_pending;
{
base::AutoLock locked(lock_);
auto key = cc.UniqueKey();
auto iter_and_result =
pending_.insert(std::make_pair(key, PendingOperationsForKey()));
PendingOperationsForKey& ops_for_key = iter_and_result.first->second;
if (!iter_and_result.second) {
if (po->op() == PendingOperation::COOKIE_DELETE) {
ops_for_key.clear();
} else if (po->op() == PendingOperation::COOKIE_UPDATEACCESS) {
if (!ops_for_key.empty() &&
ops_for_key.back()->op() == PendingOperation::COOKIE_UPDATEACCESS) {
ops_for_key.pop_back();
}
DCHECK_LE(ops_for_key.size(), 2u);
} else {
DCHECK_LE(ops_for_key.size(), 1u);
}
}
ops_for_key.push_back(std::move(po));
num_pending = ++num_pending_;
}
if (num_pending == 1) {
if (!background_task_runner()->PostDelayedTask(
FROM_HERE, base::BindOnce(&Backend::Commit, this),
base::Milliseconds(kCommitIntervalMs))) {
NOTREACHED() << "background_task_runner() is not running.";
}
} else if (num_pending == kCommitAfterBatchSize) {
PostBackgroundTask(FROM_HERE, base::BindOnce(&Backend::Commit, this));
}
}
void SQLitePersistentCookieStore::Backend::DoCommit() {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
PendingOperationsMap ops;
{
base::AutoLock locked(lock_);
pending_.swap(ops);
num_pending_ = 0;
}
if (!db() || ops.empty())
return;
sql::Statement add_statement(db()->GetCachedStatement(
SQL_FROM_HERE,
"INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"last_access_utc, has_expires, is_persistent, priority, samesite, "
"source_scheme, source_port, is_same_party, last_update_utc) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
if (!add_statement.is_valid())
return;
sql::Statement update_access_statement(db()->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE cookies SET last_access_utc=? WHERE "
"name=? AND host_key=? AND top_frame_site_key=? AND path=?"));
if (!update_access_statement.is_valid())
return;
sql::Statement delete_statement(db()->GetCachedStatement(
SQL_FROM_HERE,
"DELETE FROM cookies WHERE "
"name=? AND host_key=? AND top_frame_site_key=? AND path=?"));
if (!delete_statement.is_valid())
return;
sql::Transaction transaction(db());
if (!transaction.Begin())
return;
for (auto& kv : ops) {
for (std::unique_ptr<PendingOperation>& po_entry : kv.second) {
std::unique_ptr<PendingOperation> po(std::move(po_entry));
std::string top_frame_site_key;
if (!CookiePartitionKey::Serialize(po->cc().PartitionKey(),
top_frame_site_key)) {
continue;
}
switch (po->op()) {
case PendingOperation::COOKIE_ADD:
add_statement.Reset(true);
add_statement.BindTime(0, po->cc().CreationDate());
add_statement.BindString(1, po->cc().Domain());
add_statement.BindString(2, top_frame_site_key);
add_statement.BindString(3, po->cc().Name());
if (crypto_ && crypto_->ShouldEncrypt()) {
std::string encrypted_value;
if (!crypto_->EncryptString(po->cc().Value(), &encrypted_value)) {
DLOG(WARNING) << "Could not encrypt a cookie, skipping add.";
RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_ENCRYPT_FAILED);
continue;
}
add_statement.BindCString(4, "");
add_statement.BindBlob(5, encrypted_value);
} else {
add_statement.BindString(4, po->cc().Value());
add_statement.BindBlob(5,
base::span<uint8_t>());
}
add_statement.BindString(6, po->cc().Path());
add_statement.BindTime(7, po->cc().ExpiryDate());
add_statement.BindBool(8, po->cc().IsSecure());
add_statement.BindBool(9, po->cc().IsHttpOnly());
add_statement.BindTime(10, po->cc().LastAccessDate());
add_statement.BindBool(11, po->cc().IsPersistent());
add_statement.BindBool(12, po->cc().IsPersistent());
add_statement.BindInt(
13, CookiePriorityToDBCookiePriority(po->cc().Priority()));
add_statement.BindInt(
14, CookieSameSiteToDBCookieSameSite(po->cc().SameSite()));
add_statement.BindInt(15, static_cast<int>(po->cc().SourceScheme()));
add_statement.BindInt(16, po->cc().SourcePort());
add_statement.BindBool(17, po->cc().IsSameParty());
add_statement.BindTime(18, po->cc().LastUpdateDate());
if (!add_statement.Run()) {
DLOG(WARNING) << "Could not add a cookie to the DB.";
RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_ADD);
}
break;
case PendingOperation::COOKIE_UPDATEACCESS:
update_access_statement.Reset(true);
update_access_statement.BindTime(0, po->cc().LastAccessDate());
update_access_statement.BindString(1, po->cc().Name());
update_access_statement.BindString(2, po->cc().Domain());
update_access_statement.BindString(3, top_frame_site_key);
update_access_statement.BindString(4, po->cc().Path());
if (!update_access_statement.Run()) {
DLOG(WARNING)
<< "Could not update cookie last access time in the DB.";
RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_UPDATE_ACCESS);
}
break;
case PendingOperation::COOKIE_DELETE:
delete_statement.Reset(true);
delete_statement.BindString(0, po->cc().Name());
delete_statement.BindString(1, po->cc().Domain());
delete_statement.BindString(2, top_frame_site_key);
delete_statement.BindString(3, po->cc().Path());
if (!delete_statement.Run()) {
DLOG(WARNING) << "Could not delete a cookie from the DB.";
RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_DELETE);
}
break;
default:
NOTREACHED();
break;
}
}
}
bool commit_ok = transaction.Commit();
if (!commit_ok) {
RecordCookieCommitProblem(COOKIE_COMMIT_PROBLEM_TRANSACTION_COMMIT);
}
}
size_t SQLitePersistentCookieStore::Backend::GetQueueLengthForTesting() {
DCHECK(client_task_runner()->RunsTasksInCurrentSequence());
size_t total = 0u;
{
base::AutoLock locked(lock_);
for (const auto& key_val : pending_) {
total += key_val.second.size();
}
}
return total;
}
void SQLitePersistentCookieStore::Backend::DeleteAllInList(
const std::list<CookieOrigin>& cookies) {
if (cookies.empty())
return;
if (background_task_runner()->RunsTasksInCurrentSequence()) {
BackgroundDeleteAllInList(cookies);
} else {
PostBackgroundTask(
FROM_HERE,
base::BindOnce(&Backend::BackgroundDeleteAllInList, this, cookies));
}
}
void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
if (!db()->Execute("DELETE FROM cookies WHERE is_persistent != 1"))
LOG(WARNING) << "Unable to delete session cookies.";
}
void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
const std::list<CookieOrigin>& cookies) {
DCHECK(background_task_runner()->RunsTasksInCurrentSequence());
if (!db())
return;
Commit();
sql::Statement delete_statement(db()->GetCachedStatement(
SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND is_secure=?"));
if (!delete_statement.is_valid()) {
LOG(WARNING) << "Unable to delete cookies on shutdown.";
return;
}
sql::Transaction transaction(db());
if (!transaction.Begin()) {
LOG(WARNING) << "Unable to delete cookies on shutdown.";
return;
}
for (const auto& cookie : cookies) {
const GURL url(cookie_util::CookieOriginToURL(cookie.first, cookie.second));
if (!url.is_valid())
continue;
delete_statement.Reset(true);
delete_statement.BindString(0, cookie.first);
delete_statement.BindInt(1, cookie.second);
if (!delete_statement.Run())
NOTREACHED() << "Could not delete a cookie from the DB.";
}
if (!transaction.Commit())
LOG(WARNING) << "Unable to delete cookies on shutdown.";
}
void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
LoadedCallback loaded_callback,
bool success) {
PostClientTask(FROM_HERE,
base::BindOnce(&Backend::CompleteLoadInForeground, this,
std::move(loaded_callback), success));
}
SQLitePersistentCookieStore::SQLitePersistentCookieStore(
const base::FilePath& path,
const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
bool restore_old_session_cookies,
CookieCryptoDelegate* crypto_delegate,
bool enable_exclusive_access)
: backend_(base::MakeRefCounted<Backend>(path,
client_task_runner,
background_task_runner,
restore_old_session_cookies,
crypto_delegate,
enable_exclusive_access)) {}
void SQLitePersistentCookieStore::DeleteAllInList(
const std::list<CookieOrigin>& cookies) {
backend_->DeleteAllInList(cookies);
}
void SQLitePersistentCookieStore::Load(LoadedCallback loaded_callback,
const NetLogWithSource& net_log) {
DCHECK(!loaded_callback.is_null());
net_log_ = net_log;
net_log_.BeginEvent(NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD);
backend_->Load(base::BindOnce(&SQLitePersistentCookieStore::CompleteLoad,
this, std::move(loaded_callback)));
}
void SQLitePersistentCookieStore::LoadCookiesForKey(
const std::string& key,
LoadedCallback loaded_callback) {
DCHECK(!loaded_callback.is_null());
net_log_.AddEvent(NetLogEventType::COOKIE_PERSISTENT_STORE_KEY_LOAD_STARTED,
[&](NetLogCaptureMode capture_mode) {
return CookieKeyedLoadNetLogParams(key, capture_mode);
});
backend_->LoadCookiesForKey(
key, base::BindOnce(&SQLitePersistentCookieStore::CompleteKeyedLoad, this,
key, std::move(loaded_callback)));
}
void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
backend_->AddCookie(cc);
}
void SQLitePersistentCookieStore::UpdateCookieAccessTime(
const CanonicalCookie& cc) {
backend_->UpdateCookieAccessTime(cc);
}
void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
backend_->DeleteCookie(cc);
}
void SQLitePersistentCookieStore::SetForceKeepSessionState() {
}
void SQLitePersistentCookieStore::SetBeforeCommitCallback(
base::RepeatingClosure callback) {
backend_->SetBeforeCommitCallback(std::move(callback));
}
void SQLitePersistentCookieStore::Flush(base::OnceClosure callback) {
backend_->Flush(std::move(callback));
}
size_t SQLitePersistentCookieStore::GetQueueLengthForTesting() {
return backend_->GetQueueLengthForTesting();
}
SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
net_log_.AddEventWithStringParams(
NetLogEventType::COOKIE_PERSISTENT_STORE_CLOSED, "type",
"SQLitePersistentCookieStore");
backend_->Close();
}
void SQLitePersistentCookieStore::CompleteLoad(
LoadedCallback callback,
std::vector<std::unique_ptr<CanonicalCookie>> cookie_list) {
net_log_.EndEvent(NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD);
std::move(callback).Run(std::move(cookie_list));
}
void SQLitePersistentCookieStore::CompleteKeyedLoad(
const std::string& key,
LoadedCallback callback,
std::vector<std::unique_ptr<CanonicalCookie>> cookie_list) {
net_log_.AddEventWithStringParams(
NetLogEventType::COOKIE_PERSISTENT_STORE_KEY_LOAD_COMPLETED, "domain",
key);
std::move(callback).Run(std::move(cookie_list));
}
}