Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / net / extras / sqlite / sqlite_persistent_cookie_store.cc
blobc5fedafeea861c110735a455bf513daf5b9adcbf
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_macros.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 : delete_session_cookies_at_shutdown_(
93 ShouldDeleteSessionCookiesAtShutdown()),
94 path_(path),
95 num_pending_(0),
96 initialized_(false),
97 corruption_detected_(false),
98 restore_old_session_cookies_(restore_old_session_cookies),
99 num_cookies_read_(0),
100 client_task_runner_(client_task_runner),
101 background_task_runner_(background_task_runner),
102 num_priority_waiting_(0),
103 total_priority_requests_(0),
104 crypto_(crypto_delegate) {}
106 // Creates or loads the SQLite database.
107 void Load(const LoadedCallback& loaded_callback);
109 // Loads cookies for the domain key (eTLD+1).
110 void LoadCookiesForKey(const std::string& domain,
111 const LoadedCallback& loaded_callback);
113 // Steps through all results of |smt|, makes a cookie from each, and adds the
114 // cookie to |cookies|. This method also updates |num_cookies_read_|.
115 void MakeCookiesFromSQLStatement(std::vector<CanonicalCookie*>* cookies,
116 sql::Statement* statement);
118 // Batch a cookie addition.
119 void AddCookie(const CanonicalCookie& cc);
121 // Batch a cookie access time update.
122 void UpdateCookieAccessTime(const CanonicalCookie& cc);
124 // Batch a cookie deletion.
125 void DeleteCookie(const CanonicalCookie& cc);
127 // Commit pending operations as soon as possible.
128 void Flush(const base::Closure& callback);
130 // Commit any pending operations and close the database. This must be called
131 // before the object is destructed.
132 void Close(const base::Closure& callback);
134 // Post background delete of all cookies that match |cookies|.
135 void DeleteAllInList(const std::list<CookieOrigin>& cookies);
137 private:
138 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
140 // You should call Close() before destructing this object.
141 ~Backend() {
142 DCHECK(!db_.get()) << "Close should have already been called.";
143 DCHECK_EQ(0u, num_pending_);
144 DCHECK(pending_.empty());
146 for (CanonicalCookie* cookie : cookies_) {
147 delete cookie;
151 // Database upgrade statements.
152 bool EnsureDatabaseVersion();
154 class PendingOperation {
155 public:
156 enum OperationType {
157 COOKIE_ADD,
158 COOKIE_UPDATEACCESS,
159 COOKIE_DELETE,
162 PendingOperation(OperationType op, const CanonicalCookie& cc)
163 : op_(op), cc_(cc) {}
165 OperationType op() const { return op_; }
166 const CanonicalCookie& cc() const { return cc_; }
168 private:
169 OperationType op_;
170 CanonicalCookie cc_;
173 private:
174 // Creates or loads the SQLite database on background runner.
175 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
176 const base::Time& posted_at);
178 // Loads cookies for the domain key (eTLD+1) on background runner.
179 void LoadKeyAndNotifyInBackground(const std::string& domains,
180 const LoadedCallback& loaded_callback,
181 const base::Time& posted_at);
183 // Notifies the CookieMonster when loading completes for a specific domain key
184 // or for all domain keys. Triggers the callback and passes it all cookies
185 // that have been loaded from DB since last IO notification.
186 void Notify(const LoadedCallback& loaded_callback, bool load_success);
188 // Sends notification when the entire store is loaded, and reports metrics
189 // for the total time to load and aggregated results from any priority loads
190 // that occurred.
191 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
192 bool load_success);
194 // Sends notification when a single priority load completes. Updates priority
195 // load metric data. The data is sent only after the final load completes.
196 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
197 bool load_success,
198 const base::Time& requested_at);
200 // Sends all metrics, including posting a ReportMetricsInBackground task.
201 // Called after all priority and regular loading is complete.
202 void ReportMetrics();
204 // Sends background-runner owned metrics (i.e., the combined duration of all
205 // BG-runner tasks).
206 void ReportMetricsInBackground();
208 // Initialize the data base.
209 bool InitializeDatabase();
211 // Loads cookies for the next domain key from the DB, then either reschedules
212 // itself or schedules the provided callback to run on the client runner (if
213 // all domains are loaded).
214 void ChainLoadCookies(const LoadedCallback& loaded_callback);
216 // Load all cookies for a set of domains/hosts
217 bool LoadCookiesForDomains(const std::set<std::string>& key);
219 // Batch a cookie operation (add or delete)
220 void BatchOperation(PendingOperation::OperationType op,
221 const CanonicalCookie& cc);
222 // Commit our pending operations to the database.
223 void Commit();
224 // Close() executed on the background runner.
225 void InternalBackgroundClose(const base::Closure& callback);
227 void DeleteSessionCookiesOnStartup();
229 void DeleteSessionCookiesOnShutdown();
231 void BackgroundDeleteAllInList(const std::list<CookieOrigin>& cookies);
233 void DatabaseErrorCallback(int error, sql::Statement* stmt);
234 void KillDatabase();
236 void PostBackgroundTask(const tracked_objects::Location& origin,
237 const base::Closure& task);
238 void PostClientTask(const tracked_objects::Location& origin,
239 const base::Closure& task);
241 // Shared code between the different load strategies to be used after all
242 // cookies have been loaded.
243 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
244 bool success);
246 bool delete_session_cookies_at_shutdown_;
247 const base::FilePath path_;
248 scoped_ptr<sql::Connection> db_;
249 sql::MetaTable meta_table_;
251 typedef std::list<PendingOperation*> PendingOperationsList;
252 PendingOperationsList pending_;
253 PendingOperationsList::size_type num_pending_;
254 // Guard |cookies_|, |pending_|, |num_pending_|.
255 base::Lock lock_;
257 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
258 // the number of messages sent to the client runner. Sent back in response to
259 // individual load requests for domain keys or when all loading completes.
260 // Ownership of the cookies in this vector is transferred to the client in
261 // response to individual load requests or when all loading completes.
262 std::vector<CanonicalCookie*> cookies_;
264 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
265 std::map<std::string, std::set<std::string>> keys_to_load_;
267 // Indicates if DB has been initialized.
268 bool initialized_;
270 // Indicates if the kill-database callback has been scheduled.
271 bool corruption_detected_;
273 // If false, we should filter out session cookies when reading the DB.
274 bool restore_old_session_cookies_;
276 // The cumulative time spent loading the cookies on the background runner.
277 // Incremented and reported from the background runner.
278 base::TimeDelta cookie_load_duration_;
280 // The total number of cookies read. Incremented and reported on the
281 // background runner.
282 int num_cookies_read_;
284 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
285 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
287 // Guards the following metrics-related properties (only accessed when
288 // starting/completing priority loads or completing the total load).
289 base::Lock metrics_lock_;
290 int num_priority_waiting_;
291 // The total number of priority requests.
292 int total_priority_requests_;
293 // The time when |num_priority_waiting_| incremented to 1.
294 base::Time current_priority_wait_start_;
295 // The cumulative duration of time when |num_priority_waiting_| was greater
296 // than 1.
297 base::TimeDelta priority_wait_duration_;
298 // Class with functions that do cryptographic operations (for protecting
299 // cookies stored persistently).
301 // Not owned.
302 CookieCryptoDelegate* crypto_;
304 DISALLOW_COPY_AND_ASSIGN(Backend);
307 namespace {
309 // Version number of the database.
311 // Version 9 adds a partial index to track non-persistent cookies.
312 // Non-persistent cookies sometimes need to be deleted on startup. There are
313 // frequently few or no non-persistent cookies, so the partial index allows the
314 // deletion to be sped up or skipped, without having to page in the DB.
316 // Version 8 adds "first-party only" cookies.
318 // Version 7 adds encrypted values. Old values will continue to be used but
319 // all new values written will be encrypted on selected operating systems. New
320 // records read by old clients will simply get an empty cookie value while old
321 // records read by new clients will continue to operate with the unencrypted
322 // version. New and old clients alike will always write/update records with
323 // what they support.
325 // Version 6 adds cookie priorities. This allows developers to influence the
326 // order in which cookies are evicted in order to meet domain cookie limits.
328 // Version 5 adds the columns has_expires and is_persistent, so that the
329 // database can store session cookies as well as persistent cookies. Databases
330 // of version 5 are incompatible with older versions of code. If a database of
331 // version 5 is read by older code, session cookies will be treated as normal
332 // cookies. Currently, these fields are written, but not read anymore.
334 // In version 4, we migrated the time epoch. If you open the DB with an older
335 // version on Mac or Linux, the times will look wonky, but the file will likely
336 // be usable. On Windows version 3 and 4 are the same.
338 // Version 3 updated the database to include the last access time, so we can
339 // expire them in decreasing order of use when we've reached the maximum
340 // number of cookies.
341 const int kCurrentVersionNumber = 9;
342 const int kCompatibleVersionNumber = 5;
344 // Possible values for the 'priority' column.
345 enum DBCookiePriority {
346 kCookiePriorityLow = 0,
347 kCookiePriorityMedium = 1,
348 kCookiePriorityHigh = 2,
351 DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
352 switch (value) {
353 case COOKIE_PRIORITY_LOW:
354 return kCookiePriorityLow;
355 case COOKIE_PRIORITY_MEDIUM:
356 return kCookiePriorityMedium;
357 case COOKIE_PRIORITY_HIGH:
358 return kCookiePriorityHigh;
361 NOTREACHED();
362 return kCookiePriorityMedium;
365 CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
366 switch (value) {
367 case kCookiePriorityLow:
368 return COOKIE_PRIORITY_LOW;
369 case kCookiePriorityMedium:
370 return COOKIE_PRIORITY_MEDIUM;
371 case kCookiePriorityHigh:
372 return COOKIE_PRIORITY_HIGH;
375 NOTREACHED();
376 return COOKIE_PRIORITY_DEFAULT;
379 // Increments a specified TimeDelta by the duration between this object's
380 // constructor and destructor. Not thread safe. Multiple instances may be
381 // created with the same delta instance as long as their lifetimes are nested.
382 // The shortest lived instances have no impact.
383 class IncrementTimeDelta {
384 public:
385 explicit IncrementTimeDelta(base::TimeDelta* delta)
386 : delta_(delta), original_value_(*delta), start_(base::Time::Now()) {}
388 ~IncrementTimeDelta() {
389 *delta_ = original_value_ + base::Time::Now() - start_;
392 private:
393 base::TimeDelta* delta_;
394 base::TimeDelta original_value_;
395 base::Time start_;
397 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
400 // Initializes the cookies table, returning true on success.
401 bool InitTable(sql::Connection* db) {
402 if (db->DoesTableExist("cookies"))
403 return true;
405 std::string stmt(base::StringPrintf(
406 "CREATE TABLE cookies ("
407 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
408 "host_key TEXT NOT NULL,"
409 "name TEXT NOT NULL,"
410 "value TEXT NOT NULL,"
411 "path TEXT NOT NULL,"
412 "expires_utc INTEGER NOT NULL,"
413 "secure INTEGER NOT NULL,"
414 "httponly INTEGER NOT NULL,"
415 "last_access_utc INTEGER NOT NULL, "
416 "has_expires INTEGER NOT NULL DEFAULT 1, "
417 "persistent INTEGER NOT NULL DEFAULT 1,"
418 "priority INTEGER NOT NULL DEFAULT %d,"
419 "encrypted_value BLOB DEFAULT '',"
420 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
421 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
422 if (!db->Execute(stmt.c_str()))
423 return false;
425 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)"))
426 return false;
428 #if defined(OS_IOS)
429 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
430 // partial indices.
431 if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) {
432 #else
433 if (!db->Execute(
434 "CREATE INDEX is_transient ON cookies(persistent) "
435 "where persistent != 1")) {
436 #endif
437 return false;
440 return true;
443 } // namespace
445 void SQLitePersistentCookieStore::Backend::Load(
446 const LoadedCallback& loaded_callback) {
447 PostBackgroundTask(FROM_HERE,
448 base::Bind(&Backend::LoadAndNotifyInBackground, this,
449 loaded_callback, base::Time::Now()));
452 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
453 const std::string& key,
454 const LoadedCallback& loaded_callback) {
456 base::AutoLock locked(metrics_lock_);
457 if (num_priority_waiting_ == 0)
458 current_priority_wait_start_ = base::Time::Now();
459 num_priority_waiting_++;
460 total_priority_requests_++;
463 PostBackgroundTask(
464 FROM_HERE, base::Bind(&Backend::LoadKeyAndNotifyInBackground, this, key,
465 loaded_callback, base::Time::Now()));
468 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
469 const LoadedCallback& loaded_callback,
470 const base::Time& posted_at) {
471 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
472 IncrementTimeDelta increment(&cookie_load_duration_);
474 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoadDBQueueWait",
475 base::Time::Now() - posted_at,
476 base::TimeDelta::FromMilliseconds(1),
477 base::TimeDelta::FromMinutes(1), 50);
479 if (!InitializeDatabase()) {
480 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground,
481 this, loaded_callback, false));
482 } else {
483 ChainLoadCookies(loaded_callback);
487 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
488 const std::string& key,
489 const LoadedCallback& loaded_callback,
490 const base::Time& posted_at) {
491 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
492 IncrementTimeDelta increment(&cookie_load_duration_);
494 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeKeyLoadDBQueueWait",
495 base::Time::Now() - posted_at,
496 base::TimeDelta::FromMilliseconds(1),
497 base::TimeDelta::FromMinutes(1), 50);
499 bool success = false;
500 if (InitializeDatabase()) {
501 std::map<std::string, std::set<std::string>>::iterator it =
502 keys_to_load_.find(key);
503 if (it != keys_to_load_.end()) {
504 success = LoadCookiesForDomains(it->second);
505 keys_to_load_.erase(it);
506 } else {
507 success = true;
511 PostClientTask(
512 FROM_HERE,
513 base::Bind(
514 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
515 this, loaded_callback, success, posted_at));
518 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
519 const LoadedCallback& loaded_callback,
520 bool load_success,
521 const ::Time& requested_at) {
522 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
524 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeKeyLoadTotalWait",
525 base::Time::Now() - requested_at,
526 base::TimeDelta::FromMilliseconds(1),
527 base::TimeDelta::FromMinutes(1), 50);
529 Notify(loaded_callback, load_success);
532 base::AutoLock locked(metrics_lock_);
533 num_priority_waiting_--;
534 if (num_priority_waiting_ == 0) {
535 priority_wait_duration_ +=
536 base::Time::Now() - current_priority_wait_start_;
541 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
542 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoad", cookie_load_duration_,
543 base::TimeDelta::FromMilliseconds(1),
544 base::TimeDelta::FromMinutes(1), 50);
547 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
548 PostBackgroundTask(
549 FROM_HERE,
550 base::Bind(
551 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground,
552 this));
555 base::AutoLock locked(metrics_lock_);
556 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.PriorityBlockingTime",
557 priority_wait_duration_,
558 base::TimeDelta::FromMilliseconds(1),
559 base::TimeDelta::FromMinutes(1), 50);
561 UMA_HISTOGRAM_COUNTS_100("Cookie.PriorityLoadCount",
562 total_priority_requests_);
564 UMA_HISTOGRAM_COUNTS_10000("Cookie.NumberOfLoadedCookies",
565 num_cookies_read_);
569 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
570 const LoadedCallback& loaded_callback,
571 bool load_success) {
572 Notify(loaded_callback, load_success);
574 if (load_success)
575 ReportMetrics();
578 void SQLitePersistentCookieStore::Backend::Notify(
579 const LoadedCallback& loaded_callback,
580 bool load_success) {
581 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
583 std::vector<CanonicalCookie*> cookies;
585 base::AutoLock locked(lock_);
586 cookies.swap(cookies_);
589 loaded_callback.Run(cookies);
592 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
593 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
595 if (initialized_ || corruption_detected_) {
596 // Return false if we were previously initialized but the DB has since been
597 // closed, or if corruption caused a database reset during initialization.
598 return db_ != NULL;
601 base::Time start = base::Time::Now();
603 const base::FilePath dir = path_.DirName();
604 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
605 return false;
608 int64 db_size = 0;
609 if (base::GetFileSize(path_, &db_size))
610 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024);
612 db_.reset(new sql::Connection);
613 db_->set_histogram_tag("Cookie");
615 // Unretained to avoid a ref loop with |db_|.
616 db_->set_error_callback(
617 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
618 base::Unretained(this)));
620 if (!db_->Open(path_)) {
621 NOTREACHED() << "Unable to open cookie DB.";
622 if (corruption_detected_)
623 db_->Raze();
624 meta_table_.Reset();
625 db_.reset();
626 return false;
629 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
630 NOTREACHED() << "Unable to open cookie DB.";
631 if (corruption_detected_)
632 db_->Raze();
633 meta_table_.Reset();
634 db_.reset();
635 return false;
638 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeInitializeDB",
639 base::Time::Now() - start,
640 base::TimeDelta::FromMilliseconds(1),
641 base::TimeDelta::FromMinutes(1), 50);
643 start = base::Time::Now();
645 // Retrieve all the domains
646 sql::Statement smt(
647 db_->GetUniqueStatement("SELECT DISTINCT host_key FROM cookies"));
649 if (!smt.is_valid()) {
650 if (corruption_detected_)
651 db_->Raze();
652 meta_table_.Reset();
653 db_.reset();
654 return false;
657 std::vector<std::string> host_keys;
658 while (smt.Step())
659 host_keys.push_back(smt.ColumnString(0));
661 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoadDomains",
662 base::Time::Now() - start,
663 base::TimeDelta::FromMilliseconds(1),
664 base::TimeDelta::FromMinutes(1), 50);
666 base::Time start_parse = base::Time::Now();
668 // Build a map of domain keys (always eTLD+1) to domains.
669 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
670 const std::string& domain = host_keys[idx];
671 std::string key = registry_controlled_domains::GetDomainAndRegistry(
672 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
674 keys_to_load_[key].insert(domain);
677 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeParseDomains",
678 base::Time::Now() - start_parse,
679 base::TimeDelta::FromMilliseconds(1),
680 base::TimeDelta::FromMinutes(1), 50);
682 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeInitializeDomainMap",
683 base::Time::Now() - start,
684 base::TimeDelta::FromMilliseconds(1),
685 base::TimeDelta::FromMinutes(1), 50);
687 initialized_ = true;
689 if (!restore_old_session_cookies_)
690 DeleteSessionCookiesOnStartup();
691 return true;
694 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
695 const LoadedCallback& loaded_callback) {
696 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
697 IncrementTimeDelta increment(&cookie_load_duration_);
699 bool load_success = true;
701 if (!db_) {
702 // Close() has been called on this store.
703 load_success = false;
704 } else if (keys_to_load_.size() > 0) {
705 // Load cookies for the first domain key.
706 std::map<std::string, std::set<std::string>>::iterator it =
707 keys_to_load_.begin();
708 load_success = LoadCookiesForDomains(it->second);
709 keys_to_load_.erase(it);
712 // If load is successful and there are more domain keys to be loaded,
713 // then post a background task to continue chain-load;
714 // Otherwise notify on client runner.
715 if (load_success && keys_to_load_.size() > 0) {
716 bool success = background_task_runner_->PostDelayedTask(
717 FROM_HERE,
718 base::Bind(&Backend::ChainLoadCookies, this, loaded_callback),
719 base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds));
720 if (!success) {
721 LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
722 << " to background_task_runner_.";
724 } else {
725 FinishedLoadingCookies(loaded_callback, load_success);
729 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
730 const std::set<std::string>& domains) {
731 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
733 sql::Statement smt;
734 if (restore_old_session_cookies_) {
735 smt.Assign(db_->GetCachedStatement(
736 SQL_FROM_HERE,
737 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
738 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
739 "has_expires, persistent, priority FROM cookies WHERE host_key = ?"));
740 } else {
741 smt.Assign(db_->GetCachedStatement(
742 SQL_FROM_HERE,
743 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
744 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
745 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
746 "AND persistent = 1"));
748 if (!smt.is_valid()) {
749 smt.Clear(); // Disconnect smt_ref from db_.
750 meta_table_.Reset();
751 db_.reset();
752 return false;
755 std::vector<CanonicalCookie*> cookies;
756 std::set<std::string>::const_iterator it = domains.begin();
757 for (; it != domains.end(); ++it) {
758 smt.BindString(0, *it);
759 MakeCookiesFromSQLStatement(&cookies, &smt);
760 smt.Reset(true);
763 base::AutoLock locked(lock_);
764 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
766 return true;
769 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
770 std::vector<CanonicalCookie*>* cookies,
771 sql::Statement* statement) {
772 sql::Statement& smt = *statement;
773 while (smt.Step()) {
774 std::string value;
775 std::string encrypted_value = smt.ColumnString(4);
776 if (!encrypted_value.empty() && crypto_) {
777 if (!crypto_->DecryptString(encrypted_value, &value))
778 continue;
779 } else {
780 value = smt.ColumnString(3);
782 scoped_ptr<CanonicalCookie> cc(new CanonicalCookie(
783 // The "source" URL is not used with persisted cookies.
784 GURL(), // Source
785 smt.ColumnString(2), // name
786 value, // value
787 smt.ColumnString(1), // domain
788 smt.ColumnString(5), // path
789 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
790 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
791 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
792 smt.ColumnInt(7) != 0, // secure
793 smt.ColumnInt(8) != 0, // httponly
794 smt.ColumnInt(9) != 0, // firstpartyonly
795 DBCookiePriorityToCookiePriority(
796 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
797 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
798 << L"CreationDate too recent";
799 cookies->push_back(cc.release());
800 ++num_cookies_read_;
804 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
805 // Version check.
806 if (!meta_table_.Init(db_.get(), kCurrentVersionNumber,
807 kCompatibleVersionNumber)) {
808 return false;
811 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
812 LOG(WARNING) << "Cookie database is too new.";
813 return false;
816 int cur_version = meta_table_.GetVersionNumber();
817 if (cur_version == 2) {
818 sql::Transaction transaction(db_.get());
819 if (!transaction.Begin())
820 return false;
821 if (!db_->Execute(
822 "ALTER TABLE cookies ADD COLUMN last_access_utc "
823 "INTEGER DEFAULT 0") ||
824 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
825 LOG(WARNING) << "Unable to update cookie database to version 3.";
826 return false;
828 ++cur_version;
829 meta_table_.SetVersionNumber(cur_version);
830 meta_table_.SetCompatibleVersionNumber(
831 std::min(cur_version, kCompatibleVersionNumber));
832 transaction.Commit();
835 if (cur_version == 3) {
836 // The time epoch changed for Mac & Linux in this version to match Windows.
837 // This patch came after the main epoch change happened, so some
838 // developers have "good" times for cookies added by the more recent
839 // versions. So we have to be careful to only update times that are under
840 // the old system (which will appear to be from before 1970 in the new
841 // system). The magic number used below is 1970 in our time units.
842 sql::Transaction transaction(db_.get());
843 transaction.Begin();
844 #if !defined(OS_WIN)
845 ignore_result(db_->Execute(
846 "UPDATE cookies "
847 "SET creation_utc = creation_utc + 11644473600000000 "
848 "WHERE rowid IN "
849 "(SELECT rowid FROM cookies WHERE "
850 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
851 ignore_result(db_->Execute(
852 "UPDATE cookies "
853 "SET expires_utc = expires_utc + 11644473600000000 "
854 "WHERE rowid IN "
855 "(SELECT rowid FROM cookies WHERE "
856 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
857 ignore_result(db_->Execute(
858 "UPDATE cookies "
859 "SET last_access_utc = last_access_utc + 11644473600000000 "
860 "WHERE rowid IN "
861 "(SELECT rowid FROM cookies WHERE "
862 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
863 #endif
864 ++cur_version;
865 meta_table_.SetVersionNumber(cur_version);
866 transaction.Commit();
869 if (cur_version == 4) {
870 const base::TimeTicks start_time = base::TimeTicks::Now();
871 sql::Transaction transaction(db_.get());
872 if (!transaction.Begin())
873 return false;
874 if (!db_->Execute(
875 "ALTER TABLE cookies "
876 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
877 !db_->Execute(
878 "ALTER TABLE cookies "
879 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
880 LOG(WARNING) << "Unable to update cookie database to version 5.";
881 return false;
883 ++cur_version;
884 meta_table_.SetVersionNumber(cur_version);
885 meta_table_.SetCompatibleVersionNumber(
886 std::min(cur_version, kCompatibleVersionNumber));
887 transaction.Commit();
888 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
889 base::TimeTicks::Now() - start_time);
892 if (cur_version == 5) {
893 const base::TimeTicks start_time = base::TimeTicks::Now();
894 sql::Transaction transaction(db_.get());
895 if (!transaction.Begin())
896 return false;
897 // Alter the table to add the priority column with a default value.
898 std::string stmt(base::StringPrintf(
899 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
900 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
901 if (!db_->Execute(stmt.c_str())) {
902 LOG(WARNING) << "Unable to update cookie database to version 6.";
903 return false;
905 ++cur_version;
906 meta_table_.SetVersionNumber(cur_version);
907 meta_table_.SetCompatibleVersionNumber(
908 std::min(cur_version, kCompatibleVersionNumber));
909 transaction.Commit();
910 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
911 base::TimeTicks::Now() - start_time);
914 if (cur_version == 6) {
915 const base::TimeTicks start_time = base::TimeTicks::Now();
916 sql::Transaction transaction(db_.get());
917 if (!transaction.Begin())
918 return false;
919 // Alter the table to add empty "encrypted value" column.
920 if (!db_->Execute(
921 "ALTER TABLE cookies "
922 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
923 LOG(WARNING) << "Unable to update cookie database to version 7.";
924 return false;
926 ++cur_version;
927 meta_table_.SetVersionNumber(cur_version);
928 meta_table_.SetCompatibleVersionNumber(
929 std::min(cur_version, kCompatibleVersionNumber));
930 transaction.Commit();
931 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
932 base::TimeTicks::Now() - start_time);
935 if (cur_version == 7) {
936 const base::TimeTicks start_time = base::TimeTicks::Now();
937 sql::Transaction transaction(db_.get());
938 if (!transaction.Begin())
939 return false;
940 // Alter the table to add a 'firstpartyonly' column.
941 if (!db_->Execute(
942 "ALTER TABLE cookies "
943 "ADD COLUMN firstpartyonly INTEGER DEFAULT 0")) {
944 LOG(WARNING) << "Unable to update cookie database to version 8.";
945 return false;
947 ++cur_version;
948 meta_table_.SetVersionNumber(cur_version);
949 meta_table_.SetCompatibleVersionNumber(
950 std::min(cur_version, kCompatibleVersionNumber));
951 transaction.Commit();
952 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV8",
953 base::TimeTicks::Now() - start_time);
956 if (cur_version == 8) {
957 const base::TimeTicks start_time = base::TimeTicks::Now();
958 sql::Transaction transaction(db_.get());
959 if (!transaction.Begin())
960 return false;
962 if (!db_->Execute("DROP INDEX IF EXISTS cookie_times")) {
963 LOG(WARNING)
964 << "Unable to drop table cookie_times in update to version 9.";
965 return false;
968 if (!db_->Execute(
969 "CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)")) {
970 LOG(WARNING) << "Unable to create index domain in update to version 9.";
971 return false;
974 #if defined(OS_IOS)
975 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
976 // partial indices.
977 if (!db_->Execute(
978 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent)")) {
979 #else
980 if (!db_->Execute(
981 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent) "
982 "where persistent != 1")) {
983 #endif
984 LOG(WARNING)
985 << "Unable to create index is_transient in update to version 9.";
986 return false;
988 ++cur_version;
989 meta_table_.SetVersionNumber(cur_version);
990 meta_table_.SetCompatibleVersionNumber(
991 std::min(cur_version, kCompatibleVersionNumber));
992 transaction.Commit();
993 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV9",
994 base::TimeTicks::Now() - start_time);
997 // Put future migration cases here.
999 if (cur_version < kCurrentVersionNumber) {
1000 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
1002 meta_table_.Reset();
1003 db_.reset(new sql::Connection);
1004 if (!sql::Connection::Delete(path_) || !db_->Open(path_) ||
1005 !meta_table_.Init(db_.get(), kCurrentVersionNumber,
1006 kCompatibleVersionNumber)) {
1007 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
1008 NOTREACHED() << "Unable to reset the cookie DB.";
1009 meta_table_.Reset();
1010 db_.reset();
1011 return false;
1015 return true;
1018 void SQLitePersistentCookieStore::Backend::AddCookie(
1019 const CanonicalCookie& cc) {
1020 BatchOperation(PendingOperation::COOKIE_ADD, cc);
1023 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1024 const CanonicalCookie& cc) {
1025 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1028 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1029 const CanonicalCookie& cc) {
1030 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1033 void SQLitePersistentCookieStore::Backend::BatchOperation(
1034 PendingOperation::OperationType op,
1035 const CanonicalCookie& cc) {
1036 // Commit every 30 seconds.
1037 static const int kCommitIntervalMs = 30 * 1000;
1038 // Commit right away if we have more than 512 outstanding operations.
1039 static const size_t kCommitAfterBatchSize = 512;
1040 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1042 // We do a full copy of the cookie here, and hopefully just here.
1043 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1045 PendingOperationsList::size_type num_pending;
1047 base::AutoLock locked(lock_);
1048 pending_.push_back(po.release());
1049 num_pending = ++num_pending_;
1052 if (num_pending == 1) {
1053 // We've gotten our first entry for this batch, fire off the timer.
1054 if (!background_task_runner_->PostDelayedTask(
1055 FROM_HERE, base::Bind(&Backend::Commit, this),
1056 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
1057 NOTREACHED() << "background_task_runner_ is not running.";
1059 } else if (num_pending == kCommitAfterBatchSize) {
1060 // We've reached a big enough batch, fire off a commit now.
1061 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1065 void SQLitePersistentCookieStore::Backend::Commit() {
1066 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1068 PendingOperationsList ops;
1070 base::AutoLock locked(lock_);
1071 pending_.swap(ops);
1072 num_pending_ = 0;
1075 // Maybe an old timer fired or we are already Close()'ed.
1076 if (!db_.get() || ops.empty())
1077 return;
1079 sql::Statement add_smt(db_->GetCachedStatement(
1080 SQL_FROM_HERE,
1081 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1082 "encrypted_value, path, expires_utc, secure, httponly, firstpartyonly, "
1083 "last_access_utc, has_expires, persistent, priority) "
1084 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1085 if (!add_smt.is_valid())
1086 return;
1088 sql::Statement update_access_smt(db_->GetCachedStatement(
1089 SQL_FROM_HERE,
1090 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1091 if (!update_access_smt.is_valid())
1092 return;
1094 sql::Statement del_smt(db_->GetCachedStatement(
1095 SQL_FROM_HERE, "DELETE FROM cookies WHERE creation_utc=?"));
1096 if (!del_smt.is_valid())
1097 return;
1099 sql::Transaction transaction(db_.get());
1100 if (!transaction.Begin())
1101 return;
1103 for (PendingOperationsList::iterator it = ops.begin(); it != ops.end();
1104 ++it) {
1105 // Free the cookies as we commit them to the database.
1106 scoped_ptr<PendingOperation> po(*it);
1107 switch (po->op()) {
1108 case PendingOperation::COOKIE_ADD:
1109 add_smt.Reset(true);
1110 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1111 add_smt.BindString(1, po->cc().Domain());
1112 add_smt.BindString(2, po->cc().Name());
1113 if (crypto_ && crypto_->ShouldEncrypt()) {
1114 std::string encrypted_value;
1115 if (!crypto_->EncryptString(po->cc().Value(), &encrypted_value))
1116 continue;
1117 add_smt.BindCString(3, ""); // value
1118 // BindBlob() immediately makes an internal copy of the data.
1119 add_smt.BindBlob(4, encrypted_value.data(),
1120 static_cast<int>(encrypted_value.length()));
1121 } else {
1122 add_smt.BindString(3, po->cc().Value());
1123 add_smt.BindBlob(4, "", 0); // encrypted_value
1125 add_smt.BindString(5, po->cc().Path());
1126 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1127 add_smt.BindInt(7, po->cc().IsSecure());
1128 add_smt.BindInt(8, po->cc().IsHttpOnly());
1129 add_smt.BindInt(9, po->cc().IsFirstPartyOnly());
1130 add_smt.BindInt64(10, po->cc().LastAccessDate().ToInternalValue());
1131 add_smt.BindInt(11, po->cc().IsPersistent());
1132 add_smt.BindInt(12, po->cc().IsPersistent());
1133 add_smt.BindInt(13,
1134 CookiePriorityToDBCookiePriority(po->cc().Priority()));
1135 if (!add_smt.Run())
1136 NOTREACHED() << "Could not add a cookie to the DB.";
1137 break;
1139 case PendingOperation::COOKIE_UPDATEACCESS:
1140 update_access_smt.Reset(true);
1141 update_access_smt.BindInt64(
1142 0, po->cc().LastAccessDate().ToInternalValue());
1143 update_access_smt.BindInt64(1,
1144 po->cc().CreationDate().ToInternalValue());
1145 if (!update_access_smt.Run())
1146 NOTREACHED() << "Could not update cookie last access time in the DB.";
1147 break;
1149 case PendingOperation::COOKIE_DELETE:
1150 del_smt.Reset(true);
1151 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1152 if (!del_smt.Run())
1153 NOTREACHED() << "Could not delete a cookie from the DB.";
1154 break;
1156 default:
1157 NOTREACHED();
1158 break;
1161 bool succeeded = transaction.Commit();
1162 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1163 succeeded ? 0 : 1, 2);
1166 void SQLitePersistentCookieStore::Backend::Flush(
1167 const base::Closure& callback) {
1168 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1169 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1171 if (!callback.is_null()) {
1172 // We want the completion task to run immediately after Commit() returns.
1173 // Posting it from here means there is less chance of another task getting
1174 // onto the message queue first, than if we posted it from Commit() itself.
1175 PostBackgroundTask(FROM_HERE, callback);
1179 // Fire off a close message to the background runner. We could still have a
1180 // pending commit timer or Load operations holding references on us, but if/when
1181 // this fires we will already have been cleaned up and it will be ignored.
1182 void SQLitePersistentCookieStore::Backend::Close(
1183 const base::Closure& callback) {
1184 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1185 InternalBackgroundClose(callback);
1186 } else {
1187 // Must close the backend on the background runner.
1188 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::InternalBackgroundClose,
1189 this, callback));
1193 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose(
1194 const base::Closure& callback) {
1195 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1197 if (delete_session_cookies_at_shutdown_)
1198 DeleteSessionCookiesOnShutdown();
1200 // Commit any pending operations
1201 Commit();
1203 meta_table_.Reset();
1204 db_.reset();
1206 // We're clean now.
1207 if (!callback.is_null())
1208 callback.Run();
1211 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1212 int error,
1213 sql::Statement* stmt) {
1214 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1216 if (!sql::IsErrorCatastrophic(error))
1217 return;
1219 // TODO(shess): Running KillDatabase() multiple times should be
1220 // safe.
1221 if (corruption_detected_)
1222 return;
1224 corruption_detected_ = true;
1226 // Don't just do the close/delete here, as we are being called by |db| and
1227 // that seems dangerous.
1228 // TODO(shess): Consider just calling RazeAndClose() immediately.
1229 // db_ may not be safe to reset at this point, but RazeAndClose()
1230 // would cause the stack to unwind safely with errors.
1231 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1234 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1235 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1237 if (db_) {
1238 // This Backend will now be in-memory only. In a future run we will recreate
1239 // the database. Hopefully things go better then!
1240 bool success = db_->RazeAndClose();
1241 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1242 meta_table_.Reset();
1243 db_.reset();
1247 void SQLitePersistentCookieStore::Backend::DeleteAllInList(
1248 const std::list<CookieOrigin>& cookies) {
1249 if (cookies.empty())
1250 return;
1252 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1253 BackgroundDeleteAllInList(cookies);
1254 } else {
1255 // Perform deletion on background task runner.
1256 PostBackgroundTask(
1257 FROM_HERE,
1258 base::Bind(&Backend::BackgroundDeleteAllInList, this, cookies));
1262 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1263 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1264 base::Time start_time = base::Time::Now();
1265 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1266 LOG(WARNING) << "Unable to delete session cookies.";
1268 UMA_HISTOGRAM_TIMES("Cookie.Startup.TimeSpentDeletingCookies",
1269 base::Time::Now() - start_time);
1270 UMA_HISTOGRAM_COUNTS("Cookie.Startup.NumberOfCookiesDeleted",
1271 db_->GetLastChangeCount());
1274 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1275 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1277 if (!db_)
1278 return;
1280 base::Time start_time = base::Time::Now();
1281 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1282 LOG(WARNING) << "Unable to delete session cookies.";
1284 UMA_HISTOGRAM_TIMES("Cookie.Shutdown.TimeSpentDeletingCookies",
1285 base::Time::Now() - start_time);
1286 UMA_HISTOGRAM_COUNTS("Cookie.Shutdown.NumberOfCookiesDeleted",
1287 db_->GetLastChangeCount());
1290 void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
1291 const std::list<CookieOrigin>& cookies) {
1292 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1294 if (!db_)
1295 return;
1297 // Force a commit of any pending writes before issuing deletes.
1298 // TODO(rohitrao): Remove the need for this Commit() by instead pruning the
1299 // list of pending operations. https://crbug.com/486742.
1300 Commit();
1302 sql::Statement del_smt(db_->GetCachedStatement(
1303 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1304 if (!del_smt.is_valid()) {
1305 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1306 return;
1309 sql::Transaction transaction(db_.get());
1310 if (!transaction.Begin()) {
1311 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1312 return;
1315 for (const auto& cookie : cookies) {
1316 const GURL url(cookie_util::CookieOriginToURL(cookie.first, cookie.second));
1317 if (!url.is_valid())
1318 continue;
1320 del_smt.Reset(true);
1321 del_smt.BindString(0, cookie.first);
1322 del_smt.BindInt(1, cookie.second);
1323 if (!del_smt.Run())
1324 NOTREACHED() << "Could not delete a cookie from the DB.";
1327 if (!transaction.Commit())
1328 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1331 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1332 const tracked_objects::Location& origin,
1333 const base::Closure& task) {
1334 if (!background_task_runner_->PostTask(origin, task)) {
1335 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1336 << " to background_task_runner_.";
1340 void SQLitePersistentCookieStore::Backend::PostClientTask(
1341 const tracked_objects::Location& origin,
1342 const base::Closure& task) {
1343 if (!client_task_runner_->PostTask(origin, task)) {
1344 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1345 << " to client_task_runner_.";
1349 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1350 const LoadedCallback& loaded_callback,
1351 bool success) {
1352 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1353 loaded_callback, success));
1356 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1357 const base::FilePath& path,
1358 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1359 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1360 bool restore_old_session_cookies,
1361 CookieCryptoDelegate* crypto_delegate)
1362 : backend_(new Backend(path,
1363 client_task_runner,
1364 background_task_runner,
1365 restore_old_session_cookies,
1366 crypto_delegate)) {
1369 void SQLitePersistentCookieStore::DeleteAllInList(
1370 const std::list<CookieOrigin>& cookies) {
1371 if (backend_)
1372 backend_->DeleteAllInList(cookies);
1375 void SQLitePersistentCookieStore::Close(const base::Closure& callback) {
1376 if (backend_) {
1377 backend_->Close(callback);
1379 // We release our reference to the Backend, though it will probably still
1380 // have a reference if the background runner has not run
1381 // Backend::InternalBackgroundClose() yet.
1382 backend_ = nullptr;
1386 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1387 if (backend_)
1388 backend_->Load(loaded_callback);
1389 else
1390 loaded_callback.Run(std::vector<CanonicalCookie*>());
1393 void SQLitePersistentCookieStore::LoadCookiesForKey(
1394 const std::string& key,
1395 const LoadedCallback& loaded_callback) {
1396 if (backend_)
1397 backend_->LoadCookiesForKey(key, loaded_callback);
1398 else
1399 loaded_callback.Run(std::vector<CanonicalCookie*>());
1402 void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
1403 if (backend_)
1404 backend_->AddCookie(cc);
1407 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1408 const CanonicalCookie& cc) {
1409 if (backend_)
1410 backend_->UpdateCookieAccessTime(cc);
1413 void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
1414 if (backend_)
1415 backend_->DeleteCookie(cc);
1418 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1419 // This store never discards session-only cookies, so this call has no effect.
1422 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1423 if (backend_)
1424 backend_->Flush(callback);
1427 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1428 Close(base::Closure());
1431 } // namespace net