Include all dupe types (event when value is zero) in scan stats.
[chromium-blink-merge.git] / net / extras / sqlite / sqlite_persistent_cookie_store.cc
blob331285e79c816a6ef10c6562dd088bf17b98b429
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/extras/sqlite/sqlite_persistent_cookie_store.h"
7 #include <map>
8 #include <set>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/sequenced_task_runner.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/synchronization/lock.h"
26 #include "base/threading/sequenced_worker_pool.h"
27 #include "base/time/time.h"
28 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
29 #include "net/cookies/canonical_cookie.h"
30 #include "net/cookies/cookie_constants.h"
31 #include "net/cookies/cookie_util.h"
32 #include "net/extras/sqlite/cookie_crypto_delegate.h"
33 #include "sql/error_delegate_util.h"
34 #include "sql/meta_table.h"
35 #include "sql/statement.h"
36 #include "sql/transaction.h"
37 #include "url/gurl.h"
39 using base::Time;
41 namespace {
43 // The persistent cookie store is loaded into memory on eTLD at a time. This
44 // variable controls the delay between loading eTLDs, so as to not overload the
45 // CPU or I/O with these low priority requests immediately after start up.
46 const int kLoadDelayMilliseconds = 0;
48 const char kDeleteAtShutdown[] = "DeleteAtShutdown";
49 const char kSessionCookieDeletionStrategy[] = "SessionCookieDeletionStrategy";
51 bool ShouldDeleteSessionCookiesAtShutdown() {
52 const std::string group_name =
53 base::FieldTrialList::FindFullName(kSessionCookieDeletionStrategy);
54 return group_name == kDeleteAtShutdown;
57 } // namespace
59 namespace net {
61 // This class is designed to be shared between any client thread and the
62 // background task runner. It batches operations and commits them on a timer.
64 // SQLitePersistentCookieStore::Load is called to load all cookies. It
65 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
66 // task to the background runner. This task calls Backend::ChainLoadCookies(),
67 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
68 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
69 // posted to the client runner, which notifies the caller of
70 // SQLitePersistentCookieStore::Load that the load is complete.
72 // If a priority load request is invoked via SQLitePersistentCookieStore::
73 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
74 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
75 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
76 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
77 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
79 // Subsequent to loading, mutations may be queued by any thread using
80 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
81 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
82 // whichever occurs first.
83 class SQLitePersistentCookieStore::Backend
84 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
85 public:
86 Backend(
87 const base::FilePath& path,
88 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
89 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
90 bool restore_old_session_cookies,
91 CookieCryptoDelegate* crypto_delegate)
92 : path_(path),
93 num_pending_(0),
94 initialized_(false),
95 corruption_detected_(false),
96 restore_old_session_cookies_(restore_old_session_cookies),
97 num_cookies_read_(0),
98 client_task_runner_(client_task_runner),
99 background_task_runner_(background_task_runner),
100 num_priority_waiting_(0),
101 total_priority_requests_(0),
102 crypto_(crypto_delegate) {}
104 // Creates or loads the SQLite database.
105 void Load(const LoadedCallback& loaded_callback);
107 // Loads cookies for the domain key (eTLD+1).
108 void LoadCookiesForKey(const std::string& domain,
109 const LoadedCallback& loaded_callback);
111 // Steps through all results of |smt|, makes a cookie from each, and adds the
112 // cookie to |cookies|. This method also updates |num_cookies_read_|.
113 void MakeCookiesFromSQLStatement(std::vector<CanonicalCookie*>* cookies,
114 sql::Statement* statement);
116 // Batch a cookie addition.
117 void AddCookie(const CanonicalCookie& cc);
119 // Batch a cookie access time update.
120 void UpdateCookieAccessTime(const CanonicalCookie& cc);
122 // Batch a cookie deletion.
123 void DeleteCookie(const CanonicalCookie& cc);
125 // Commit pending operations as soon as possible.
126 void Flush(const base::Closure& callback);
128 // Commit any pending operations and close the database. This must be called
129 // before the object is destructed.
130 void Close();
132 // Post background delete of all cookies that match |cookies|.
133 void DeleteAllInList(const std::list<CookieOrigin>& cookies);
135 private:
136 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
138 // You should call Close() before destructing this object.
139 ~Backend() {
140 DCHECK(!db_.get()) << "Close should have already been called.";
141 DCHECK_EQ(0u, num_pending_);
142 DCHECK(pending_.empty());
144 for (CanonicalCookie* cookie : cookies_) {
145 delete cookie;
149 // Database upgrade statements.
150 bool EnsureDatabaseVersion();
152 class PendingOperation {
153 public:
154 enum OperationType {
155 COOKIE_ADD,
156 COOKIE_UPDATEACCESS,
157 COOKIE_DELETE,
160 PendingOperation(OperationType op, const CanonicalCookie& cc)
161 : op_(op), cc_(cc) {}
163 OperationType op() const { return op_; }
164 const CanonicalCookie& cc() const { return cc_; }
166 private:
167 OperationType op_;
168 CanonicalCookie cc_;
171 private:
172 // Creates or loads the SQLite database on background runner.
173 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
174 const base::Time& posted_at);
176 // Loads cookies for the domain key (eTLD+1) on background runner.
177 void LoadKeyAndNotifyInBackground(const std::string& domains,
178 const LoadedCallback& loaded_callback,
179 const base::Time& posted_at);
181 // Notifies the CookieMonster when loading completes for a specific domain key
182 // or for all domain keys. Triggers the callback and passes it all cookies
183 // that have been loaded from DB since last IO notification.
184 void Notify(const LoadedCallback& loaded_callback, bool load_success);
186 // Sends notification when the entire store is loaded, and reports metrics
187 // for the total time to load and aggregated results from any priority loads
188 // that occurred.
189 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
190 bool load_success);
192 // Sends notification when a single priority load completes. Updates priority
193 // load metric data. The data is sent only after the final load completes.
194 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
195 bool load_success,
196 const base::Time& requested_at);
198 // Sends all metrics, including posting a ReportMetricsInBackground task.
199 // Called after all priority and regular loading is complete.
200 void ReportMetrics();
202 // Sends background-runner owned metrics (i.e., the combined duration of all
203 // BG-runner tasks).
204 void ReportMetricsInBackground();
206 // Initialize the data base.
207 bool InitializeDatabase();
209 // Loads cookies for the next domain key from the DB, then either reschedules
210 // itself or schedules the provided callback to run on the client runner (if
211 // all domains are loaded).
212 void ChainLoadCookies(const LoadedCallback& loaded_callback);
214 // Load all cookies for a set of domains/hosts
215 bool LoadCookiesForDomains(const std::set<std::string>& key);
217 // Batch a cookie operation (add or delete)
218 void BatchOperation(PendingOperation::OperationType op,
219 const CanonicalCookie& cc);
220 // Commit our pending operations to the database.
221 void Commit();
222 // Close() executed on the background runner.
223 void InternalBackgroundClose();
225 void DeleteSessionCookiesOnStartup();
227 void DeleteSessionCookiesOnShutdown();
229 void BackgroundDeleteAllInList(const std::list<CookieOrigin>& cookies);
231 void DatabaseErrorCallback(int error, sql::Statement* stmt);
232 void KillDatabase();
234 void PostBackgroundTask(const tracked_objects::Location& origin,
235 const base::Closure& task);
236 void PostClientTask(const tracked_objects::Location& origin,
237 const base::Closure& task);
239 // Shared code between the different load strategies to be used after all
240 // cookies have been loaded.
241 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
242 bool success);
244 const base::FilePath path_;
245 scoped_ptr<sql::Connection> db_;
246 sql::MetaTable meta_table_;
248 typedef std::list<PendingOperation*> PendingOperationsList;
249 PendingOperationsList pending_;
250 PendingOperationsList::size_type num_pending_;
251 // Guard |cookies_|, |pending_|, |num_pending_|.
252 base::Lock lock_;
254 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
255 // the number of messages sent to the client runner. Sent back in response to
256 // individual load requests for domain keys or when all loading completes.
257 // Ownership of the cookies in this vector is transferred to the client in
258 // response to individual load requests or when all loading completes.
259 std::vector<CanonicalCookie*> cookies_;
261 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
262 std::map<std::string, std::set<std::string>> keys_to_load_;
264 // Indicates if DB has been initialized.
265 bool initialized_;
267 // Indicates if the kill-database callback has been scheduled.
268 bool corruption_detected_;
270 // If false, we should filter out session cookies when reading the DB.
271 bool restore_old_session_cookies_;
273 // The cumulative time spent loading the cookies on the background runner.
274 // Incremented and reported from the background runner.
275 base::TimeDelta cookie_load_duration_;
277 // The total number of cookies read. Incremented and reported on the
278 // background runner.
279 int num_cookies_read_;
281 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
282 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
284 // Guards the following metrics-related properties (only accessed when
285 // starting/completing priority loads or completing the total load).
286 base::Lock metrics_lock_;
287 int num_priority_waiting_;
288 // The total number of priority requests.
289 int total_priority_requests_;
290 // The time when |num_priority_waiting_| incremented to 1.
291 base::Time current_priority_wait_start_;
292 // The cumulative duration of time when |num_priority_waiting_| was greater
293 // than 1.
294 base::TimeDelta priority_wait_duration_;
295 // Class with functions that do cryptographic operations (for protecting
296 // cookies stored persistently).
298 // Not owned.
299 CookieCryptoDelegate* crypto_;
301 DISALLOW_COPY_AND_ASSIGN(Backend);
304 namespace {
306 // Version number of the database.
308 // Version 9 adds a partial index to track non-persistent cookies.
309 // Non-persistent cookies sometimes need to be deleted on startup. There are
310 // frequently few or no non-persistent cookies, so the partial index allows the
311 // deletion to be sped up or skipped, without having to page in the DB.
313 // Version 8 adds "first-party only" cookies.
315 // Version 7 adds encrypted values. Old values will continue to be used but
316 // all new values written will be encrypted on selected operating systems. New
317 // records read by old clients will simply get an empty cookie value while old
318 // records read by new clients will continue to operate with the unencrypted
319 // version. New and old clients alike will always write/update records with
320 // what they support.
322 // Version 6 adds cookie priorities. This allows developers to influence the
323 // order in which cookies are evicted in order to meet domain cookie limits.
325 // Version 5 adds the columns has_expires and is_persistent, so that the
326 // database can store session cookies as well as persistent cookies. Databases
327 // of version 5 are incompatible with older versions of code. If a database of
328 // version 5 is read by older code, session cookies will be treated as normal
329 // cookies. Currently, these fields are written, but not read anymore.
331 // In version 4, we migrated the time epoch. If you open the DB with an older
332 // version on Mac or Linux, the times will look wonky, but the file will likely
333 // be usable. On Windows version 3 and 4 are the same.
335 // Version 3 updated the database to include the last access time, so we can
336 // expire them in decreasing order of use when we've reached the maximum
337 // number of cookies.
338 const int kCurrentVersionNumber = 9;
339 const int kCompatibleVersionNumber = 5;
341 // Possible values for the 'priority' column.
342 enum DBCookiePriority {
343 kCookiePriorityLow = 0,
344 kCookiePriorityMedium = 1,
345 kCookiePriorityHigh = 2,
348 DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
349 switch (value) {
350 case COOKIE_PRIORITY_LOW:
351 return kCookiePriorityLow;
352 case COOKIE_PRIORITY_MEDIUM:
353 return kCookiePriorityMedium;
354 case COOKIE_PRIORITY_HIGH:
355 return kCookiePriorityHigh;
358 NOTREACHED();
359 return kCookiePriorityMedium;
362 CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
363 switch (value) {
364 case kCookiePriorityLow:
365 return COOKIE_PRIORITY_LOW;
366 case kCookiePriorityMedium:
367 return COOKIE_PRIORITY_MEDIUM;
368 case kCookiePriorityHigh:
369 return COOKIE_PRIORITY_HIGH;
372 NOTREACHED();
373 return COOKIE_PRIORITY_DEFAULT;
376 // Increments a specified TimeDelta by the duration between this object's
377 // constructor and destructor. Not thread safe. Multiple instances may be
378 // created with the same delta instance as long as their lifetimes are nested.
379 // The shortest lived instances have no impact.
380 class IncrementTimeDelta {
381 public:
382 explicit IncrementTimeDelta(base::TimeDelta* delta)
383 : delta_(delta), original_value_(*delta), start_(base::Time::Now()) {}
385 ~IncrementTimeDelta() {
386 *delta_ = original_value_ + base::Time::Now() - start_;
389 private:
390 base::TimeDelta* delta_;
391 base::TimeDelta original_value_;
392 base::Time start_;
394 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
397 // Initializes the cookies table, returning true on success.
398 bool InitTable(sql::Connection* db) {
399 if (db->DoesTableExist("cookies"))
400 return true;
402 std::string stmt(base::StringPrintf(
403 "CREATE TABLE cookies ("
404 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
405 "host_key TEXT NOT NULL,"
406 "name TEXT NOT NULL,"
407 "value TEXT NOT NULL,"
408 "path TEXT NOT NULL,"
409 "expires_utc INTEGER NOT NULL,"
410 "secure INTEGER NOT NULL,"
411 "httponly INTEGER NOT NULL,"
412 "last_access_utc INTEGER NOT NULL, "
413 "has_expires INTEGER NOT NULL DEFAULT 1, "
414 "persistent INTEGER NOT NULL DEFAULT 1,"
415 "priority INTEGER NOT NULL DEFAULT %d,"
416 "encrypted_value BLOB DEFAULT '',"
417 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
418 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
419 if (!db->Execute(stmt.c_str()))
420 return false;
422 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)"))
423 return false;
425 #if defined(OS_IOS)
426 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
427 // partial indices.
428 if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) {
429 #else
430 if (!db->Execute(
431 "CREATE INDEX is_transient ON cookies(persistent) "
432 "where persistent != 1")) {
433 #endif
434 return false;
437 return true;
440 } // namespace
442 void SQLitePersistentCookieStore::Backend::Load(
443 const LoadedCallback& loaded_callback) {
444 PostBackgroundTask(FROM_HERE,
445 base::Bind(&Backend::LoadAndNotifyInBackground, this,
446 loaded_callback, base::Time::Now()));
449 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
450 const std::string& key,
451 const LoadedCallback& loaded_callback) {
453 base::AutoLock locked(metrics_lock_);
454 if (num_priority_waiting_ == 0)
455 current_priority_wait_start_ = base::Time::Now();
456 num_priority_waiting_++;
457 total_priority_requests_++;
460 PostBackgroundTask(
461 FROM_HERE, base::Bind(&Backend::LoadKeyAndNotifyInBackground, this, key,
462 loaded_callback, base::Time::Now()));
465 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
466 const LoadedCallback& loaded_callback,
467 const base::Time& posted_at) {
468 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
469 IncrementTimeDelta increment(&cookie_load_duration_);
471 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoadDBQueueWait",
472 base::Time::Now() - posted_at,
473 base::TimeDelta::FromMilliseconds(1),
474 base::TimeDelta::FromMinutes(1), 50);
476 if (!InitializeDatabase()) {
477 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground,
478 this, loaded_callback, false));
479 } else {
480 ChainLoadCookies(loaded_callback);
484 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
485 const std::string& key,
486 const LoadedCallback& loaded_callback,
487 const base::Time& posted_at) {
488 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
489 IncrementTimeDelta increment(&cookie_load_duration_);
491 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeKeyLoadDBQueueWait",
492 base::Time::Now() - posted_at,
493 base::TimeDelta::FromMilliseconds(1),
494 base::TimeDelta::FromMinutes(1), 50);
496 bool success = false;
497 if (InitializeDatabase()) {
498 std::map<std::string, std::set<std::string>>::iterator it =
499 keys_to_load_.find(key);
500 if (it != keys_to_load_.end()) {
501 success = LoadCookiesForDomains(it->second);
502 keys_to_load_.erase(it);
503 } else {
504 success = true;
508 PostClientTask(
509 FROM_HERE,
510 base::Bind(
511 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
512 this, loaded_callback, success, posted_at));
515 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
516 const LoadedCallback& loaded_callback,
517 bool load_success,
518 const ::Time& requested_at) {
519 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
521 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeKeyLoadTotalWait",
522 base::Time::Now() - requested_at,
523 base::TimeDelta::FromMilliseconds(1),
524 base::TimeDelta::FromMinutes(1), 50);
526 Notify(loaded_callback, load_success);
529 base::AutoLock locked(metrics_lock_);
530 num_priority_waiting_--;
531 if (num_priority_waiting_ == 0) {
532 priority_wait_duration_ +=
533 base::Time::Now() - current_priority_wait_start_;
538 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
539 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoad", cookie_load_duration_,
540 base::TimeDelta::FromMilliseconds(1),
541 base::TimeDelta::FromMinutes(1), 50);
544 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
545 PostBackgroundTask(
546 FROM_HERE,
547 base::Bind(
548 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground,
549 this));
552 base::AutoLock locked(metrics_lock_);
553 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.PriorityBlockingTime",
554 priority_wait_duration_,
555 base::TimeDelta::FromMilliseconds(1),
556 base::TimeDelta::FromMinutes(1), 50);
558 UMA_HISTOGRAM_COUNTS_100("Cookie.PriorityLoadCount",
559 total_priority_requests_);
561 UMA_HISTOGRAM_COUNTS_10000("Cookie.NumberOfLoadedCookies",
562 num_cookies_read_);
566 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
567 const LoadedCallback& loaded_callback,
568 bool load_success) {
569 Notify(loaded_callback, load_success);
571 if (load_success)
572 ReportMetrics();
575 void SQLitePersistentCookieStore::Backend::Notify(
576 const LoadedCallback& loaded_callback,
577 bool load_success) {
578 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
580 std::vector<CanonicalCookie*> cookies;
582 base::AutoLock locked(lock_);
583 cookies.swap(cookies_);
586 loaded_callback.Run(cookies);
589 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
590 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
592 if (initialized_ || corruption_detected_) {
593 // Return false if we were previously initialized but the DB has since been
594 // closed, or if corruption caused a database reset during initialization.
595 return db_ != NULL;
598 base::Time start = base::Time::Now();
600 const base::FilePath dir = path_.DirName();
601 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
602 return false;
605 int64 db_size = 0;
606 if (base::GetFileSize(path_, &db_size))
607 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024);
609 db_.reset(new sql::Connection);
610 db_->set_histogram_tag("Cookie");
612 // Unretained to avoid a ref loop with |db_|.
613 db_->set_error_callback(
614 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
615 base::Unretained(this)));
617 if (!db_->Open(path_)) {
618 NOTREACHED() << "Unable to open cookie DB.";
619 if (corruption_detected_)
620 db_->Raze();
621 meta_table_.Reset();
622 db_.reset();
623 return false;
626 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
627 NOTREACHED() << "Unable to open cookie DB.";
628 if (corruption_detected_)
629 db_->Raze();
630 meta_table_.Reset();
631 db_.reset();
632 return false;
635 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeInitializeDB",
636 base::Time::Now() - start,
637 base::TimeDelta::FromMilliseconds(1),
638 base::TimeDelta::FromMinutes(1), 50);
640 start = base::Time::Now();
642 // Retrieve all the domains
643 sql::Statement smt(
644 db_->GetUniqueStatement("SELECT DISTINCT host_key FROM cookies"));
646 if (!smt.is_valid()) {
647 if (corruption_detected_)
648 db_->Raze();
649 meta_table_.Reset();
650 db_.reset();
651 return false;
654 std::vector<std::string> host_keys;
655 while (smt.Step())
656 host_keys.push_back(smt.ColumnString(0));
658 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoadDomains",
659 base::Time::Now() - start,
660 base::TimeDelta::FromMilliseconds(1),
661 base::TimeDelta::FromMinutes(1), 50);
663 base::Time start_parse = base::Time::Now();
665 // Build a map of domain keys (always eTLD+1) to domains.
666 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
667 const std::string& domain = host_keys[idx];
668 std::string key = registry_controlled_domains::GetDomainAndRegistry(
669 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
671 keys_to_load_[key].insert(domain);
674 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeParseDomains",
675 base::Time::Now() - start_parse,
676 base::TimeDelta::FromMilliseconds(1),
677 base::TimeDelta::FromMinutes(1), 50);
679 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeInitializeDomainMap",
680 base::Time::Now() - start,
681 base::TimeDelta::FromMilliseconds(1),
682 base::TimeDelta::FromMinutes(1), 50);
684 initialized_ = true;
686 if (!restore_old_session_cookies_)
687 DeleteSessionCookiesOnStartup();
688 return true;
691 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
692 const LoadedCallback& loaded_callback) {
693 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
694 IncrementTimeDelta increment(&cookie_load_duration_);
696 bool load_success = true;
698 if (!db_) {
699 // Close() has been called on this store.
700 load_success = false;
701 } else if (keys_to_load_.size() > 0) {
702 // Load cookies for the first domain key.
703 std::map<std::string, std::set<std::string>>::iterator it =
704 keys_to_load_.begin();
705 load_success = LoadCookiesForDomains(it->second);
706 keys_to_load_.erase(it);
709 // If load is successful and there are more domain keys to be loaded,
710 // then post a background task to continue chain-load;
711 // Otherwise notify on client runner.
712 if (load_success && keys_to_load_.size() > 0) {
713 bool success = background_task_runner_->PostDelayedTask(
714 FROM_HERE,
715 base::Bind(&Backend::ChainLoadCookies, this, loaded_callback),
716 base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds));
717 if (!success) {
718 LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
719 << " to background_task_runner_.";
721 } else {
722 FinishedLoadingCookies(loaded_callback, load_success);
726 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
727 const std::set<std::string>& domains) {
728 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
730 sql::Statement smt;
731 if (restore_old_session_cookies_) {
732 smt.Assign(db_->GetCachedStatement(
733 SQL_FROM_HERE,
734 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
735 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
736 "has_expires, persistent, priority FROM cookies WHERE host_key = ?"));
737 } else {
738 smt.Assign(db_->GetCachedStatement(
739 SQL_FROM_HERE,
740 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
741 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
742 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
743 "AND persistent = 1"));
745 if (!smt.is_valid()) {
746 smt.Clear(); // Disconnect smt_ref from db_.
747 meta_table_.Reset();
748 db_.reset();
749 return false;
752 std::vector<CanonicalCookie*> cookies;
753 std::set<std::string>::const_iterator it = domains.begin();
754 for (; it != domains.end(); ++it) {
755 smt.BindString(0, *it);
756 MakeCookiesFromSQLStatement(&cookies, &smt);
757 smt.Reset(true);
760 base::AutoLock locked(lock_);
761 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
763 return true;
766 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
767 std::vector<CanonicalCookie*>* cookies,
768 sql::Statement* statement) {
769 sql::Statement& smt = *statement;
770 while (smt.Step()) {
771 std::string value;
772 std::string encrypted_value = smt.ColumnString(4);
773 if (!encrypted_value.empty() && crypto_) {
774 crypto_->DecryptString(encrypted_value, &value);
775 } else {
776 DCHECK(encrypted_value.empty());
777 value = smt.ColumnString(3);
779 scoped_ptr<CanonicalCookie> cc(new CanonicalCookie(
780 // The "source" URL is not used with persisted cookies.
781 GURL(), // Source
782 smt.ColumnString(2), // name
783 value, // value
784 smt.ColumnString(1), // domain
785 smt.ColumnString(5), // path
786 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
787 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
788 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
789 smt.ColumnInt(7) != 0, // secure
790 smt.ColumnInt(8) != 0, // httponly
791 smt.ColumnInt(9) != 0, // firstpartyonly
792 DBCookiePriorityToCookiePriority(
793 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
794 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
795 << L"CreationDate too recent";
796 cookies->push_back(cc.release());
797 ++num_cookies_read_;
801 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
802 // Version check.
803 if (!meta_table_.Init(db_.get(), kCurrentVersionNumber,
804 kCompatibleVersionNumber)) {
805 return false;
808 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
809 LOG(WARNING) << "Cookie database is too new.";
810 return false;
813 int cur_version = meta_table_.GetVersionNumber();
814 if (cur_version == 2) {
815 sql::Transaction transaction(db_.get());
816 if (!transaction.Begin())
817 return false;
818 if (!db_->Execute(
819 "ALTER TABLE cookies ADD COLUMN last_access_utc "
820 "INTEGER DEFAULT 0") ||
821 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
822 LOG(WARNING) << "Unable to update cookie database to version 3.";
823 return false;
825 ++cur_version;
826 meta_table_.SetVersionNumber(cur_version);
827 meta_table_.SetCompatibleVersionNumber(
828 std::min(cur_version, kCompatibleVersionNumber));
829 transaction.Commit();
832 if (cur_version == 3) {
833 // The time epoch changed for Mac & Linux in this version to match Windows.
834 // This patch came after the main epoch change happened, so some
835 // developers have "good" times for cookies added by the more recent
836 // versions. So we have to be careful to only update times that are under
837 // the old system (which will appear to be from before 1970 in the new
838 // system). The magic number used below is 1970 in our time units.
839 sql::Transaction transaction(db_.get());
840 transaction.Begin();
841 #if !defined(OS_WIN)
842 ignore_result(db_->Execute(
843 "UPDATE cookies "
844 "SET creation_utc = creation_utc + 11644473600000000 "
845 "WHERE rowid IN "
846 "(SELECT rowid FROM cookies WHERE "
847 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
848 ignore_result(db_->Execute(
849 "UPDATE cookies "
850 "SET expires_utc = expires_utc + 11644473600000000 "
851 "WHERE rowid IN "
852 "(SELECT rowid FROM cookies WHERE "
853 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
854 ignore_result(db_->Execute(
855 "UPDATE cookies "
856 "SET last_access_utc = last_access_utc + 11644473600000000 "
857 "WHERE rowid IN "
858 "(SELECT rowid FROM cookies WHERE "
859 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
860 #endif
861 ++cur_version;
862 meta_table_.SetVersionNumber(cur_version);
863 transaction.Commit();
866 if (cur_version == 4) {
867 const base::TimeTicks start_time = base::TimeTicks::Now();
868 sql::Transaction transaction(db_.get());
869 if (!transaction.Begin())
870 return false;
871 if (!db_->Execute(
872 "ALTER TABLE cookies "
873 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
874 !db_->Execute(
875 "ALTER TABLE cookies "
876 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
877 LOG(WARNING) << "Unable to update cookie database to version 5.";
878 return false;
880 ++cur_version;
881 meta_table_.SetVersionNumber(cur_version);
882 meta_table_.SetCompatibleVersionNumber(
883 std::min(cur_version, kCompatibleVersionNumber));
884 transaction.Commit();
885 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
886 base::TimeTicks::Now() - start_time);
889 if (cur_version == 5) {
890 const base::TimeTicks start_time = base::TimeTicks::Now();
891 sql::Transaction transaction(db_.get());
892 if (!transaction.Begin())
893 return false;
894 // Alter the table to add the priority column with a default value.
895 std::string stmt(base::StringPrintf(
896 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
897 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
898 if (!db_->Execute(stmt.c_str())) {
899 LOG(WARNING) << "Unable to update cookie database to version 6.";
900 return false;
902 ++cur_version;
903 meta_table_.SetVersionNumber(cur_version);
904 meta_table_.SetCompatibleVersionNumber(
905 std::min(cur_version, kCompatibleVersionNumber));
906 transaction.Commit();
907 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
908 base::TimeTicks::Now() - start_time);
911 if (cur_version == 6) {
912 const base::TimeTicks start_time = base::TimeTicks::Now();
913 sql::Transaction transaction(db_.get());
914 if (!transaction.Begin())
915 return false;
916 // Alter the table to add empty "encrypted value" column.
917 if (!db_->Execute(
918 "ALTER TABLE cookies "
919 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
920 LOG(WARNING) << "Unable to update cookie database to version 7.";
921 return false;
923 ++cur_version;
924 meta_table_.SetVersionNumber(cur_version);
925 meta_table_.SetCompatibleVersionNumber(
926 std::min(cur_version, kCompatibleVersionNumber));
927 transaction.Commit();
928 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
929 base::TimeTicks::Now() - start_time);
932 if (cur_version == 7) {
933 const base::TimeTicks start_time = base::TimeTicks::Now();
934 sql::Transaction transaction(db_.get());
935 if (!transaction.Begin())
936 return false;
937 // Alter the table to add a 'firstpartyonly' column.
938 if (!db_->Execute(
939 "ALTER TABLE cookies "
940 "ADD COLUMN firstpartyonly INTEGER DEFAULT 0")) {
941 LOG(WARNING) << "Unable to update cookie database to version 8.";
942 return false;
944 ++cur_version;
945 meta_table_.SetVersionNumber(cur_version);
946 meta_table_.SetCompatibleVersionNumber(
947 std::min(cur_version, kCompatibleVersionNumber));
948 transaction.Commit();
949 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV8",
950 base::TimeTicks::Now() - start_time);
953 if (cur_version == 8) {
954 const base::TimeTicks start_time = base::TimeTicks::Now();
955 sql::Transaction transaction(db_.get());
956 if (!transaction.Begin())
957 return false;
959 if (!db_->Execute("DROP INDEX IF EXISTS cookie_times")) {
960 LOG(WARNING)
961 << "Unable to drop table cookie_times in update to version 9.";
962 return false;
965 if (!db_->Execute(
966 "CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)")) {
967 LOG(WARNING) << "Unable to create index domain in update to version 9.";
968 return false;
971 #if defined(OS_IOS)
972 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
973 // partial indices.
974 if (!db_->Execute(
975 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent)")) {
976 #else
977 if (!db_->Execute(
978 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent) "
979 "where persistent != 1")) {
980 #endif
981 LOG(WARNING)
982 << "Unable to create index is_transient in update to version 9.";
983 return false;
985 ++cur_version;
986 meta_table_.SetVersionNumber(cur_version);
987 meta_table_.SetCompatibleVersionNumber(
988 std::min(cur_version, kCompatibleVersionNumber));
989 transaction.Commit();
990 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV9",
991 base::TimeTicks::Now() - start_time);
994 // Put future migration cases here.
996 if (cur_version < kCurrentVersionNumber) {
997 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
999 meta_table_.Reset();
1000 db_.reset(new sql::Connection);
1001 if (!sql::Connection::Delete(path_) || !db_->Open(path_) ||
1002 !meta_table_.Init(db_.get(), kCurrentVersionNumber,
1003 kCompatibleVersionNumber)) {
1004 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
1005 NOTREACHED() << "Unable to reset the cookie DB.";
1006 meta_table_.Reset();
1007 db_.reset();
1008 return false;
1012 return true;
1015 void SQLitePersistentCookieStore::Backend::AddCookie(
1016 const CanonicalCookie& cc) {
1017 BatchOperation(PendingOperation::COOKIE_ADD, cc);
1020 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1021 const CanonicalCookie& cc) {
1022 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1025 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1026 const CanonicalCookie& cc) {
1027 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1030 void SQLitePersistentCookieStore::Backend::BatchOperation(
1031 PendingOperation::OperationType op,
1032 const CanonicalCookie& cc) {
1033 // Commit every 30 seconds.
1034 static const int kCommitIntervalMs = 30 * 1000;
1035 // Commit right away if we have more than 512 outstanding operations.
1036 static const size_t kCommitAfterBatchSize = 512;
1037 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1039 // We do a full copy of the cookie here, and hopefully just here.
1040 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1042 PendingOperationsList::size_type num_pending;
1044 base::AutoLock locked(lock_);
1045 pending_.push_back(po.release());
1046 num_pending = ++num_pending_;
1049 if (num_pending == 1) {
1050 // We've gotten our first entry for this batch, fire off the timer.
1051 if (!background_task_runner_->PostDelayedTask(
1052 FROM_HERE, base::Bind(&Backend::Commit, this),
1053 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
1054 NOTREACHED() << "background_task_runner_ is not running.";
1056 } else if (num_pending == kCommitAfterBatchSize) {
1057 // We've reached a big enough batch, fire off a commit now.
1058 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1062 void SQLitePersistentCookieStore::Backend::Commit() {
1063 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1065 PendingOperationsList ops;
1067 base::AutoLock locked(lock_);
1068 pending_.swap(ops);
1069 num_pending_ = 0;
1072 // Maybe an old timer fired or we are already Close()'ed.
1073 if (!db_.get() || ops.empty())
1074 return;
1076 sql::Statement add_smt(db_->GetCachedStatement(
1077 SQL_FROM_HERE,
1078 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1079 "encrypted_value, path, expires_utc, secure, httponly, firstpartyonly, "
1080 "last_access_utc, has_expires, persistent, priority) "
1081 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1082 if (!add_smt.is_valid())
1083 return;
1085 sql::Statement update_access_smt(db_->GetCachedStatement(
1086 SQL_FROM_HERE,
1087 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1088 if (!update_access_smt.is_valid())
1089 return;
1091 sql::Statement del_smt(db_->GetCachedStatement(
1092 SQL_FROM_HERE, "DELETE FROM cookies WHERE creation_utc=?"));
1093 if (!del_smt.is_valid())
1094 return;
1096 sql::Transaction transaction(db_.get());
1097 if (!transaction.Begin())
1098 return;
1100 for (PendingOperationsList::iterator it = ops.begin(); it != ops.end();
1101 ++it) {
1102 // Free the cookies as we commit them to the database.
1103 scoped_ptr<PendingOperation> po(*it);
1104 switch (po->op()) {
1105 case PendingOperation::COOKIE_ADD:
1106 add_smt.Reset(true);
1107 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1108 add_smt.BindString(1, po->cc().Domain());
1109 add_smt.BindString(2, po->cc().Name());
1110 if (crypto_) {
1111 std::string encrypted_value;
1112 add_smt.BindCString(3, ""); // value
1113 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1114 // BindBlob() immediately makes an internal copy of the data.
1115 add_smt.BindBlob(4, encrypted_value.data(),
1116 static_cast<int>(encrypted_value.length()));
1117 } else {
1118 add_smt.BindString(3, po->cc().Value());
1119 add_smt.BindBlob(4, "", 0); // encrypted_value
1121 add_smt.BindString(5, po->cc().Path());
1122 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1123 add_smt.BindInt(7, po->cc().IsSecure());
1124 add_smt.BindInt(8, po->cc().IsHttpOnly());
1125 add_smt.BindInt(9, po->cc().IsFirstPartyOnly());
1126 add_smt.BindInt64(10, po->cc().LastAccessDate().ToInternalValue());
1127 add_smt.BindInt(11, po->cc().IsPersistent());
1128 add_smt.BindInt(12, po->cc().IsPersistent());
1129 add_smt.BindInt(13,
1130 CookiePriorityToDBCookiePriority(po->cc().Priority()));
1131 if (!add_smt.Run())
1132 NOTREACHED() << "Could not add a cookie to the DB.";
1133 break;
1135 case PendingOperation::COOKIE_UPDATEACCESS:
1136 update_access_smt.Reset(true);
1137 update_access_smt.BindInt64(
1138 0, po->cc().LastAccessDate().ToInternalValue());
1139 update_access_smt.BindInt64(1,
1140 po->cc().CreationDate().ToInternalValue());
1141 if (!update_access_smt.Run())
1142 NOTREACHED() << "Could not update cookie last access time in the DB.";
1143 break;
1145 case PendingOperation::COOKIE_DELETE:
1146 del_smt.Reset(true);
1147 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1148 if (!del_smt.Run())
1149 NOTREACHED() << "Could not delete a cookie from the DB.";
1150 break;
1152 default:
1153 NOTREACHED();
1154 break;
1157 bool succeeded = transaction.Commit();
1158 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1159 succeeded ? 0 : 1, 2);
1162 void SQLitePersistentCookieStore::Backend::Flush(
1163 const base::Closure& callback) {
1164 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1165 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1167 if (!callback.is_null()) {
1168 // We want the completion task to run immediately after Commit() returns.
1169 // Posting it from here means there is less chance of another task getting
1170 // onto the message queue first, than if we posted it from Commit() itself.
1171 PostBackgroundTask(FROM_HERE, callback);
1175 // Fire off a close message to the background runner. We could still have a
1176 // pending commit timer or Load operations holding references on us, but if/when
1177 // this fires we will already have been cleaned up and it will be ignored.
1178 void SQLitePersistentCookieStore::Backend::Close() {
1179 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1180 InternalBackgroundClose();
1181 } else {
1182 // Must close the backend on the background runner.
1183 PostBackgroundTask(FROM_HERE,
1184 base::Bind(&Backend::InternalBackgroundClose, this));
1188 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1189 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1191 if (ShouldDeleteSessionCookiesAtShutdown())
1192 DeleteSessionCookiesOnShutdown();
1194 // Commit any pending operations
1195 Commit();
1197 meta_table_.Reset();
1198 db_.reset();
1201 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1202 int error,
1203 sql::Statement* stmt) {
1204 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1206 if (!sql::IsErrorCatastrophic(error))
1207 return;
1209 // TODO(shess): Running KillDatabase() multiple times should be
1210 // safe.
1211 if (corruption_detected_)
1212 return;
1214 corruption_detected_ = true;
1216 // Don't just do the close/delete here, as we are being called by |db| and
1217 // that seems dangerous.
1218 // TODO(shess): Consider just calling RazeAndClose() immediately.
1219 // db_ may not be safe to reset at this point, but RazeAndClose()
1220 // would cause the stack to unwind safely with errors.
1221 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1224 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1225 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1227 if (db_) {
1228 // This Backend will now be in-memory only. In a future run we will recreate
1229 // the database. Hopefully things go better then!
1230 bool success = db_->RazeAndClose();
1231 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1232 meta_table_.Reset();
1233 db_.reset();
1237 void SQLitePersistentCookieStore::Backend::DeleteAllInList(
1238 const std::list<CookieOrigin>& cookies) {
1239 if (cookies.empty())
1240 return;
1242 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1243 BackgroundDeleteAllInList(cookies);
1244 } else {
1245 // Perform deletion on background task runner.
1246 PostBackgroundTask(
1247 FROM_HERE,
1248 base::Bind(&Backend::BackgroundDeleteAllInList, this, cookies));
1252 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1253 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1254 base::Time start_time = base::Time::Now();
1255 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1256 LOG(WARNING) << "Unable to delete session cookies.";
1258 UMA_HISTOGRAM_TIMES("Cookie.Startup.TimeSpentDeletingCookies",
1259 base::Time::Now() - start_time);
1260 UMA_HISTOGRAM_COUNTS("Cookie.Startup.NumberOfCookiesDeleted",
1261 db_->GetLastChangeCount());
1264 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1265 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1267 if (!db_)
1268 return;
1270 base::Time start_time = base::Time::Now();
1271 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1272 LOG(WARNING) << "Unable to delete session cookies.";
1274 UMA_HISTOGRAM_TIMES("Cookie.Shutdown.TimeSpentDeletingCookies",
1275 base::Time::Now() - start_time);
1276 UMA_HISTOGRAM_COUNTS("Cookie.Shutdown.NumberOfCookiesDeleted",
1277 db_->GetLastChangeCount());
1280 void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
1281 const std::list<CookieOrigin>& cookies) {
1282 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1284 if (!db_)
1285 return;
1287 // Force a commit of any pending writes before issuing deletes.
1288 // TODO(rohitrao): Remove the need for this Commit() by instead pruning the
1289 // list of pending operations. https://crbug.com/486742.
1290 Commit();
1292 sql::Statement del_smt(db_->GetCachedStatement(
1293 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1294 if (!del_smt.is_valid()) {
1295 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1296 return;
1299 sql::Transaction transaction(db_.get());
1300 if (!transaction.Begin()) {
1301 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1302 return;
1305 for (const auto& cookie : cookies) {
1306 const GURL url(cookie_util::CookieOriginToURL(cookie.first, cookie.second));
1307 if (!url.is_valid())
1308 continue;
1310 del_smt.Reset(true);
1311 del_smt.BindString(0, cookie.first);
1312 del_smt.BindInt(1, cookie.second);
1313 if (!del_smt.Run())
1314 NOTREACHED() << "Could not delete a cookie from the DB.";
1317 if (!transaction.Commit())
1318 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1321 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1322 const tracked_objects::Location& origin,
1323 const base::Closure& task) {
1324 if (!background_task_runner_->PostTask(origin, task)) {
1325 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1326 << " to background_task_runner_.";
1330 void SQLitePersistentCookieStore::Backend::PostClientTask(
1331 const tracked_objects::Location& origin,
1332 const base::Closure& task) {
1333 if (!client_task_runner_->PostTask(origin, task)) {
1334 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1335 << " to client_task_runner_.";
1339 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1340 const LoadedCallback& loaded_callback,
1341 bool success) {
1342 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1343 loaded_callback, success));
1346 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1347 const base::FilePath& path,
1348 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1349 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1350 bool restore_old_session_cookies,
1351 CookieCryptoDelegate* crypto_delegate)
1352 : backend_(new Backend(path,
1353 client_task_runner,
1354 background_task_runner,
1355 restore_old_session_cookies,
1356 crypto_delegate)) {
1359 void SQLitePersistentCookieStore::DeleteAllInList(
1360 const std::list<CookieOrigin>& cookies) {
1361 backend_->DeleteAllInList(cookies);
1364 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1365 backend_->Load(loaded_callback);
1368 void SQLitePersistentCookieStore::LoadCookiesForKey(
1369 const std::string& key,
1370 const LoadedCallback& loaded_callback) {
1371 backend_->LoadCookiesForKey(key, loaded_callback);
1374 void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
1375 backend_->AddCookie(cc);
1378 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1379 const CanonicalCookie& cc) {
1380 backend_->UpdateCookieAccessTime(cc);
1383 void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
1384 backend_->DeleteCookie(cc);
1387 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1388 // This store never discards session-only cookies, so this call has no effect.
1391 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1392 backend_->Flush(callback);
1395 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1396 backend_->Close();
1397 // We release our reference to the Backend, though it will probably still have
1398 // a reference if the background runner has not run Close() yet.
1401 } // namespace net