Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / content / browser / net / sqlite_persistent_cookie_store.cc
blob5da609bb67f72da1a964f60e0c6f67c8d5b41b74
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 "content/browser/net/sqlite_persistent_cookie_store.h"
7 #include <list>
8 #include <map>
9 #include <set>
10 #include <utility>
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/callback.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/location.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/sequenced_task_runner.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/synchronization/lock.h"
28 #include "base/threading/sequenced_worker_pool.h"
29 #include "base/time/time.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/cookie_store_factory.h"
32 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
33 #include "net/cookies/canonical_cookie.h"
34 #include "net/cookies/cookie_constants.h"
35 #include "net/cookies/cookie_util.h"
36 #include "net/extras/sqlite/cookie_crypto_delegate.h"
37 #include "sql/error_delegate_util.h"
38 #include "sql/meta_table.h"
39 #include "sql/statement.h"
40 #include "sql/transaction.h"
41 #include "storage/browser/quota/special_storage_policy.h"
42 #include "third_party/sqlite/sqlite3.h"
43 #include "url/gurl.h"
45 using base::Time;
47 namespace {
49 // The persistent cookie store is loaded into memory on eTLD at a time. This
50 // variable controls the delay between loading eTLDs, so as to not overload the
51 // CPU or I/O with these low priority requests immediately after start up.
52 const int kLoadDelayMilliseconds = 0;
54 } // namespace
56 namespace content {
58 // This class is designed to be shared between any client thread and the
59 // background task runner. It batches operations and commits them on a timer.
61 // SQLitePersistentCookieStore::Load is called to load all cookies. It
62 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
63 // task to the background runner. This task calls Backend::ChainLoadCookies(),
64 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
65 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
66 // posted to the client runner, which notifies the caller of
67 // SQLitePersistentCookieStore::Load that the load is complete.
69 // If a priority load request is invoked via SQLitePersistentCookieStore::
70 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
71 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
72 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
73 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
74 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
76 // Subsequent to loading, mutations may be queued by any thread using
77 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
78 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
79 // whichever occurs first.
80 class SQLitePersistentCookieStore::Backend
81 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
82 public:
83 Backend(
84 const base::FilePath& path,
85 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
86 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
87 bool restore_old_session_cookies,
88 storage::SpecialStoragePolicy* special_storage_policy,
89 net::CookieCryptoDelegate* crypto_delegate)
90 : path_(path),
91 num_pending_(0),
92 force_keep_session_state_(false),
93 initialized_(false),
94 corruption_detected_(false),
95 restore_old_session_cookies_(restore_old_session_cookies),
96 special_storage_policy_(special_storage_policy),
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 |cookies_per_origin_| and
113 // |num_cookies_read_|.
114 void MakeCookiesFromSQLStatement(std::vector<net::CanonicalCookie*>* cookies,
115 sql::Statement* statement);
117 // Batch a cookie addition.
118 void AddCookie(const net::CanonicalCookie& cc);
120 // Batch a cookie access time update.
121 void UpdateCookieAccessTime(const net::CanonicalCookie& cc);
123 // Batch a cookie deletion.
124 void DeleteCookie(const net::CanonicalCookie& cc);
126 // Commit pending operations as soon as possible.
127 void Flush(const base::Closure& callback);
129 // Commit any pending operations and close the database. This must be called
130 // before the object is destructed.
131 void Close();
133 void SetForceKeepSessionState();
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(num_pending_ == 0 && pending_.empty());
143 for (net::CanonicalCookie* cookie : cookies_) {
144 delete cookie;
148 // Database upgrade statements.
149 bool EnsureDatabaseVersion();
151 class PendingOperation {
152 public:
153 typedef enum {
154 COOKIE_ADD,
155 COOKIE_UPDATEACCESS,
156 COOKIE_DELETE,
157 } OperationType;
159 PendingOperation(OperationType op, const net::CanonicalCookie& cc)
160 : op_(op), cc_(cc) { }
162 OperationType op() const { return op_; }
163 const net::CanonicalCookie& cc() const { return cc_; }
165 private:
166 OperationType op_;
167 net::CanonicalCookie cc_;
170 private:
171 // Creates or loads the SQLite database on background runner.
172 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
173 const base::Time& posted_at);
175 // Loads cookies for the domain key (eTLD+1) on background runner.
176 void LoadKeyAndNotifyInBackground(const std::string& domains,
177 const LoadedCallback& loaded_callback,
178 const base::Time& posted_at);
180 // Notifies the CookieMonster when loading completes for a specific domain key
181 // or for all domain keys. Triggers the callback and passes it all cookies
182 // that have been loaded from DB since last IO notification.
183 void Notify(const LoadedCallback& loaded_callback, bool load_success);
185 // Sends notification when the entire store is loaded, and reports metrics
186 // for the total time to load and aggregated results from any priority loads
187 // that occurred.
188 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
189 bool load_success);
191 // Sends notification when a single priority load completes. Updates priority
192 // load metric data. The data is sent only after the final load completes.
193 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
194 bool load_success,
195 const base::Time& requested_at);
197 // Sends all metrics, including posting a ReportMetricsInBackground task.
198 // Called after all priority and regular loading is complete.
199 void ReportMetrics();
201 // Sends background-runner owned metrics (i.e., the combined duration of all
202 // BG-runner tasks).
203 void ReportMetricsInBackground();
205 // Initialize the data base.
206 bool InitializeDatabase();
208 // Loads cookies for the next domain key from the DB, then either reschedules
209 // itself or schedules the provided callback to run on the client runner (if
210 // all domains are loaded).
211 void ChainLoadCookies(const LoadedCallback& loaded_callback);
213 // Load all cookies for a set of domains/hosts
214 bool LoadCookiesForDomains(const std::set<std::string>& key);
216 // Batch a cookie operation (add or delete)
217 void BatchOperation(PendingOperation::OperationType op,
218 const net::CanonicalCookie& cc);
219 // Commit our pending operations to the database.
220 void Commit();
221 // Close() executed on the background runner.
222 void InternalBackgroundClose();
224 void DeleteSessionCookiesOnStartup();
226 void DeleteSessionCookiesOnShutdown();
228 void DatabaseErrorCallback(int error, sql::Statement* stmt);
229 void KillDatabase();
231 void PostBackgroundTask(const tracked_objects::Location& origin,
232 const base::Closure& task);
233 void PostClientTask(const tracked_objects::Location& origin,
234 const base::Closure& task);
236 // Shared code between the different load strategies to be used after all
237 // cookies have been loaded.
238 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
239 bool success);
241 base::FilePath path_;
242 scoped_ptr<sql::Connection> db_;
243 sql::MetaTable meta_table_;
245 typedef std::list<PendingOperation*> PendingOperationsList;
246 PendingOperationsList pending_;
247 PendingOperationsList::size_type num_pending_;
248 // True if the persistent store should skip delete on exit rules.
249 bool force_keep_session_state_;
250 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
251 base::Lock lock_;
253 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
254 // the number of messages sent to the client runner. Sent back in response to
255 // individual load requests for domain keys or when all loading completes.
256 // Ownership of the cookies in this vector is transferred to the client in
257 // response to individual load requests or when all loading completes.
258 std::vector<net::CanonicalCookie*> cookies_;
260 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
261 std::map<std::string, std::set<std::string> > keys_to_load_;
263 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
264 // database.
265 typedef std::pair<std::string, bool> CookieOrigin;
266 typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
267 CookiesPerOriginMap cookies_per_origin_;
269 // Indicates if DB has been initialized.
270 bool initialized_;
272 // Indicates if the kill-database callback has been scheduled.
273 bool corruption_detected_;
275 // If false, we should filter out session cookies when reading the DB.
276 bool restore_old_session_cookies_;
278 // Policy defining what data is deleted on shutdown.
279 scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_;
281 // The cumulative time spent loading the cookies on the background runner.
282 // Incremented and reported from the background runner.
283 base::TimeDelta cookie_load_duration_;
285 // The total number of cookies read. Incremented and reported on the
286 // background runner.
287 int num_cookies_read_;
289 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
290 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
292 // Guards the following metrics-related properties (only accessed when
293 // starting/completing priority loads or completing the total load).
294 base::Lock metrics_lock_;
295 int num_priority_waiting_;
296 // The total number of priority requests.
297 int total_priority_requests_;
298 // The time when |num_priority_waiting_| incremented to 1.
299 base::Time current_priority_wait_start_;
300 // The cumulative duration of time when |num_priority_waiting_| was greater
301 // than 1.
302 base::TimeDelta priority_wait_duration_;
303 // Class with functions that do cryptographic operations (for protecting
304 // cookies stored persistently).
306 // Not owned.
307 net::CookieCryptoDelegate* crypto_;
309 DISALLOW_COPY_AND_ASSIGN(Backend);
312 namespace {
314 // Version number of the database.
316 // Version 9 adds a partial index to track non-persistent cookies.
317 // Non-persistent cookies sometimes need to be deleted on startup. There are
318 // frequently few or no non-persistent cookies, so the partial index allows the
319 // deletion to be sped up or skipped, without having to page in the DB.
321 // Version 8 adds "first-party only" cookies.
323 // Version 7 adds encrypted values. Old values will continue to be used but
324 // all new values written will be encrypted on selected operating systems. New
325 // records read by old clients will simply get an empty cookie value while old
326 // records read by new clients will continue to operate with the unencrypted
327 // version. New and old clients alike will always write/update records with
328 // what they support.
330 // Version 6 adds cookie priorities. This allows developers to influence the
331 // order in which cookies are evicted in order to meet domain cookie limits.
333 // Version 5 adds the columns has_expires and is_persistent, so that the
334 // database can store session cookies as well as persistent cookies. Databases
335 // of version 5 are incompatible with older versions of code. If a database of
336 // version 5 is read by older code, session cookies will be treated as normal
337 // cookies. Currently, these fields are written, but not read anymore.
339 // In version 4, we migrated the time epoch. If you open the DB with an older
340 // version on Mac or Linux, the times will look wonky, but the file will likely
341 // be usable. On Windows version 3 and 4 are the same.
343 // Version 3 updated the database to include the last access time, so we can
344 // expire them in decreasing order of use when we've reached the maximum
345 // number of cookies.
346 const int kCurrentVersionNumber = 9;
347 const int kCompatibleVersionNumber = 5;
349 // Possible values for the 'priority' column.
350 enum DBCookiePriority {
351 kCookiePriorityLow = 0,
352 kCookiePriorityMedium = 1,
353 kCookiePriorityHigh = 2,
356 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) {
357 switch (value) {
358 case net::COOKIE_PRIORITY_LOW:
359 return kCookiePriorityLow;
360 case net::COOKIE_PRIORITY_MEDIUM:
361 return kCookiePriorityMedium;
362 case net::COOKIE_PRIORITY_HIGH:
363 return kCookiePriorityHigh;
366 NOTREACHED();
367 return kCookiePriorityMedium;
370 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
371 switch (value) {
372 case kCookiePriorityLow:
373 return net::COOKIE_PRIORITY_LOW;
374 case kCookiePriorityMedium:
375 return net::COOKIE_PRIORITY_MEDIUM;
376 case kCookiePriorityHigh:
377 return net::COOKIE_PRIORITY_HIGH;
380 NOTREACHED();
381 return net::COOKIE_PRIORITY_DEFAULT;
384 // Increments a specified TimeDelta by the duration between this object's
385 // constructor and destructor. Not thread safe. Multiple instances may be
386 // created with the same delta instance as long as their lifetimes are nested.
387 // The shortest lived instances have no impact.
388 class IncrementTimeDelta {
389 public:
390 explicit IncrementTimeDelta(base::TimeDelta* delta) :
391 delta_(delta),
392 original_value_(*delta),
393 start_(base::Time::Now()) {}
395 ~IncrementTimeDelta() {
396 *delta_ = original_value_ + base::Time::Now() - start_;
399 private:
400 base::TimeDelta* delta_;
401 base::TimeDelta original_value_;
402 base::Time start_;
404 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
407 // Initializes the cookies table, returning true on success.
408 bool InitTable(sql::Connection* db) {
409 if (db->DoesTableExist("cookies"))
410 return true;
412 std::string stmt(base::StringPrintf(
413 "CREATE TABLE cookies ("
414 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
415 "host_key TEXT NOT NULL,"
416 "name TEXT NOT NULL,"
417 "value TEXT NOT NULL,"
418 "path TEXT NOT NULL,"
419 "expires_utc INTEGER NOT NULL,"
420 "secure INTEGER NOT NULL,"
421 "httponly INTEGER NOT NULL,"
422 "last_access_utc INTEGER NOT NULL, "
423 "has_expires INTEGER NOT NULL DEFAULT 1, "
424 "persistent INTEGER NOT NULL DEFAULT 1,"
425 "priority INTEGER NOT NULL DEFAULT %d,"
426 "encrypted_value BLOB DEFAULT '',"
427 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
428 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
429 if (!db->Execute(stmt.c_str()))
430 return false;
432 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)"))
433 return false;
435 if (!db->Execute(
436 "CREATE INDEX is_transient ON cookies(persistent) "
437 "where persistent != 1")) {
438 return false;
441 return true;
444 } // namespace
446 void SQLitePersistentCookieStore::Backend::Load(
447 const LoadedCallback& loaded_callback) {
448 // This function should be called only once per instance.
449 DCHECK(!db_.get());
450 PostBackgroundTask(FROM_HERE, base::Bind(
451 &Backend::LoadAndNotifyInBackground, this,
452 loaded_callback, base::Time::Now()));
455 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
456 const std::string& key,
457 const LoadedCallback& loaded_callback) {
459 base::AutoLock locked(metrics_lock_);
460 if (num_priority_waiting_ == 0)
461 current_priority_wait_start_ = base::Time::Now();
462 num_priority_waiting_++;
463 total_priority_requests_++;
466 PostBackgroundTask(FROM_HERE, base::Bind(
467 &Backend::LoadKeyAndNotifyInBackground,
468 this, key, loaded_callback, base::Time::Now()));
471 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
472 const LoadedCallback& loaded_callback, const base::Time& posted_at) {
473 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
474 IncrementTimeDelta increment(&cookie_load_duration_);
476 UMA_HISTOGRAM_CUSTOM_TIMES(
477 "Cookie.TimeLoadDBQueueWait",
478 base::Time::Now() - posted_at,
479 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
480 50);
482 if (!InitializeDatabase()) {
483 PostClientTask(FROM_HERE, base::Bind(
484 &Backend::CompleteLoadInForeground, this, loaded_callback, false));
485 } else {
486 ChainLoadCookies(loaded_callback);
490 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
491 const std::string& key,
492 const LoadedCallback& loaded_callback,
493 const base::Time& posted_at) {
494 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
495 IncrementTimeDelta increment(&cookie_load_duration_);
497 UMA_HISTOGRAM_CUSTOM_TIMES(
498 "Cookie.TimeKeyLoadDBQueueWait",
499 base::Time::Now() - posted_at,
500 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
501 50);
503 bool success = false;
504 if (InitializeDatabase()) {
505 std::map<std::string, std::set<std::string> >::iterator
506 it = keys_to_load_.find(key);
507 if (it != keys_to_load_.end()) {
508 success = LoadCookiesForDomains(it->second);
509 keys_to_load_.erase(it);
510 } else {
511 success = true;
515 PostClientTask(FROM_HERE, base::Bind(
516 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
517 this, loaded_callback, success, posted_at));
520 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
521 const LoadedCallback& loaded_callback,
522 bool load_success,
523 const::Time& requested_at) {
524 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
526 UMA_HISTOGRAM_CUSTOM_TIMES(
527 "Cookie.TimeKeyLoadTotalWait",
528 base::Time::Now() - requested_at,
529 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
530 50);
532 Notify(loaded_callback, load_success);
535 base::AutoLock locked(metrics_lock_);
536 num_priority_waiting_--;
537 if (num_priority_waiting_ == 0) {
538 priority_wait_duration_ +=
539 base::Time::Now() - current_priority_wait_start_;
545 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
546 UMA_HISTOGRAM_CUSTOM_TIMES(
547 "Cookie.TimeLoad",
548 cookie_load_duration_,
549 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
550 50);
553 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
554 PostBackgroundTask(FROM_HERE, base::Bind(
555 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground, this));
558 base::AutoLock locked(metrics_lock_);
559 UMA_HISTOGRAM_CUSTOM_TIMES(
560 "Cookie.PriorityBlockingTime",
561 priority_wait_duration_,
562 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
563 50);
565 UMA_HISTOGRAM_COUNTS_100(
566 "Cookie.PriorityLoadCount",
567 total_priority_requests_);
569 UMA_HISTOGRAM_COUNTS_10000(
570 "Cookie.NumberOfLoadedCookies",
571 num_cookies_read_);
575 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
576 const LoadedCallback& loaded_callback, bool load_success) {
577 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457528 is fixed.
578 tracked_objects::ScopedTracker tracking_profile(
579 FROM_HERE_WITH_EXPLICIT_FUNCTION(
580 "457528 "
581 "SQLitePersistentCookieStore::Backend::CompleteLoadInForeground"));
582 Notify(loaded_callback, load_success);
584 if (load_success)
585 ReportMetrics();
588 void SQLitePersistentCookieStore::Backend::Notify(
589 const LoadedCallback& loaded_callback,
590 bool load_success) {
591 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
593 std::vector<net::CanonicalCookie*> cookies;
595 base::AutoLock locked(lock_);
596 cookies.swap(cookies_);
599 loaded_callback.Run(cookies);
602 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
603 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
605 if (initialized_ || corruption_detected_) {
606 // Return false if we were previously initialized but the DB has since been
607 // closed, or if corruption caused a database reset during initialization.
608 return db_ != NULL;
611 base::Time start = base::Time::Now();
613 const base::FilePath dir = path_.DirName();
614 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
615 return false;
618 int64 db_size = 0;
619 if (base::GetFileSize(path_, &db_size))
620 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024 );
622 db_.reset(new sql::Connection);
623 db_->set_histogram_tag("Cookie");
625 // Unretained to avoid a ref loop with |db_|.
626 db_->set_error_callback(
627 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
628 base::Unretained(this)));
630 if (!db_->Open(path_)) {
631 NOTREACHED() << "Unable to open cookie DB.";
632 if (corruption_detected_)
633 db_->Raze();
634 meta_table_.Reset();
635 db_.reset();
636 return false;
639 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
640 NOTREACHED() << "Unable to open cookie DB.";
641 if (corruption_detected_)
642 db_->Raze();
643 meta_table_.Reset();
644 db_.reset();
645 return false;
648 UMA_HISTOGRAM_CUSTOM_TIMES(
649 "Cookie.TimeInitializeDB",
650 base::Time::Now() - start,
651 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
652 50);
654 start = base::Time::Now();
656 // Retrieve all the domains
657 sql::Statement smt(db_->GetUniqueStatement(
658 "SELECT DISTINCT host_key FROM cookies"));
660 if (!smt.is_valid()) {
661 if (corruption_detected_)
662 db_->Raze();
663 meta_table_.Reset();
664 db_.reset();
665 return false;
668 std::vector<std::string> host_keys;
669 while (smt.Step())
670 host_keys.push_back(smt.ColumnString(0));
672 UMA_HISTOGRAM_CUSTOM_TIMES(
673 "Cookie.TimeLoadDomains",
674 base::Time::Now() - start,
675 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
676 50);
678 base::Time start_parse = base::Time::Now();
680 // Build a map of domain keys (always eTLD+1) to domains.
681 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
682 const std::string& domain = host_keys[idx];
683 std::string key =
684 net::registry_controlled_domains::GetDomainAndRegistry(
685 domain,
686 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
688 keys_to_load_[key].insert(domain);
691 UMA_HISTOGRAM_CUSTOM_TIMES(
692 "Cookie.TimeParseDomains",
693 base::Time::Now() - start_parse,
694 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
695 50);
697 UMA_HISTOGRAM_CUSTOM_TIMES(
698 "Cookie.TimeInitializeDomainMap",
699 base::Time::Now() - start,
700 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
701 50);
703 initialized_ = true;
704 return true;
707 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
708 const LoadedCallback& loaded_callback) {
709 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
710 IncrementTimeDelta increment(&cookie_load_duration_);
712 bool load_success = true;
714 if (!db_) {
715 // Close() has been called on this store.
716 load_success = false;
717 } else if (keys_to_load_.size() > 0) {
718 // Load cookies for the first domain key.
719 std::map<std::string, std::set<std::string> >::iterator
720 it = keys_to_load_.begin();
721 load_success = LoadCookiesForDomains(it->second);
722 keys_to_load_.erase(it);
725 // If load is successful and there are more domain keys to be loaded,
726 // then post a background task to continue chain-load;
727 // Otherwise notify on client runner.
728 if (load_success && keys_to_load_.size() > 0) {
729 bool success = background_task_runner_->PostDelayedTask(
730 FROM_HERE,
731 base::Bind(&Backend::ChainLoadCookies, this, loaded_callback),
732 base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds));
733 if (!success) {
734 LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
735 << " to background_task_runner_.";
737 } else {
738 FinishedLoadingCookies(loaded_callback, load_success);
742 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
743 const std::set<std::string>& domains) {
744 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
746 sql::Statement smt;
747 if (restore_old_session_cookies_) {
748 smt.Assign(db_->GetCachedStatement(
749 SQL_FROM_HERE,
750 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
751 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
752 "has_expires, persistent, priority FROM cookies WHERE host_key = ?"));
753 } else {
754 smt.Assign(db_->GetCachedStatement(
755 SQL_FROM_HERE,
756 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
757 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
758 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
759 "AND persistent = 1"));
761 if (!smt.is_valid()) {
762 smt.Clear(); // Disconnect smt_ref from db_.
763 meta_table_.Reset();
764 db_.reset();
765 return false;
768 std::vector<net::CanonicalCookie*> cookies;
769 std::set<std::string>::const_iterator it = domains.begin();
770 for (; it != domains.end(); ++it) {
771 smt.BindString(0, *it);
772 MakeCookiesFromSQLStatement(&cookies, &smt);
773 smt.Reset(true);
776 base::AutoLock locked(lock_);
777 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
779 return true;
782 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
783 std::vector<net::CanonicalCookie*>* cookies,
784 sql::Statement* statement) {
785 sql::Statement& smt = *statement;
786 while (smt.Step()) {
787 std::string value;
788 std::string encrypted_value = smt.ColumnString(4);
789 if (!encrypted_value.empty() && crypto_) {
790 crypto_->DecryptString(encrypted_value, &value);
791 } else {
792 DCHECK(encrypted_value.empty());
793 value = smt.ColumnString(3);
795 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie(
796 // The "source" URL is not used with persisted cookies.
797 GURL(), // Source
798 smt.ColumnString(2), // name
799 value, // value
800 smt.ColumnString(1), // domain
801 smt.ColumnString(5), // path
802 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
803 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
804 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
805 smt.ColumnInt(7) != 0, // secure
806 smt.ColumnInt(8) != 0, // httponly
807 smt.ColumnInt(9) != 0, // firstpartyonly
808 DBCookiePriorityToCookiePriority(
809 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
810 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
811 << L"CreationDate too recent";
812 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
813 cookies->push_back(cc.release());
814 ++num_cookies_read_;
818 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
819 // Version check.
820 if (!meta_table_.Init(
821 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
822 return false;
825 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
826 LOG(WARNING) << "Cookie database is too new.";
827 return false;
830 int cur_version = meta_table_.GetVersionNumber();
831 if (cur_version == 2) {
832 sql::Transaction transaction(db_.get());
833 if (!transaction.Begin())
834 return false;
835 if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
836 "INTEGER DEFAULT 0") ||
837 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
838 LOG(WARNING) << "Unable to update cookie database to version 3.";
839 return false;
841 ++cur_version;
842 meta_table_.SetVersionNumber(cur_version);
843 meta_table_.SetCompatibleVersionNumber(
844 std::min(cur_version, kCompatibleVersionNumber));
845 transaction.Commit();
848 if (cur_version == 3) {
849 // The time epoch changed for Mac & Linux in this version to match Windows.
850 // This patch came after the main epoch change happened, so some
851 // developers have "good" times for cookies added by the more recent
852 // versions. So we have to be careful to only update times that are under
853 // the old system (which will appear to be from before 1970 in the new
854 // system). The magic number used below is 1970 in our time units.
855 sql::Transaction transaction(db_.get());
856 transaction.Begin();
857 #if !defined(OS_WIN)
858 ignore_result(db_->Execute(
859 "UPDATE cookies "
860 "SET creation_utc = creation_utc + 11644473600000000 "
861 "WHERE rowid IN "
862 "(SELECT rowid FROM cookies WHERE "
863 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
864 ignore_result(db_->Execute(
865 "UPDATE cookies "
866 "SET expires_utc = expires_utc + 11644473600000000 "
867 "WHERE rowid IN "
868 "(SELECT rowid FROM cookies WHERE "
869 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
870 ignore_result(db_->Execute(
871 "UPDATE cookies "
872 "SET last_access_utc = last_access_utc + 11644473600000000 "
873 "WHERE rowid IN "
874 "(SELECT rowid FROM cookies WHERE "
875 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
876 #endif
877 ++cur_version;
878 meta_table_.SetVersionNumber(cur_version);
879 transaction.Commit();
882 if (cur_version == 4) {
883 const base::TimeTicks start_time = base::TimeTicks::Now();
884 sql::Transaction transaction(db_.get());
885 if (!transaction.Begin())
886 return false;
887 if (!db_->Execute("ALTER TABLE cookies "
888 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
889 !db_->Execute("ALTER TABLE cookies "
890 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
891 LOG(WARNING) << "Unable to update cookie database to version 5.";
892 return false;
894 ++cur_version;
895 meta_table_.SetVersionNumber(cur_version);
896 meta_table_.SetCompatibleVersionNumber(
897 std::min(cur_version, kCompatibleVersionNumber));
898 transaction.Commit();
899 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
900 base::TimeTicks::Now() - start_time);
903 if (cur_version == 5) {
904 const base::TimeTicks start_time = base::TimeTicks::Now();
905 sql::Transaction transaction(db_.get());
906 if (!transaction.Begin())
907 return false;
908 // Alter the table to add the priority column with a default value.
909 std::string stmt(base::StringPrintf(
910 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
911 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
912 if (!db_->Execute(stmt.c_str())) {
913 LOG(WARNING) << "Unable to update cookie database to version 6.";
914 return false;
916 ++cur_version;
917 meta_table_.SetVersionNumber(cur_version);
918 meta_table_.SetCompatibleVersionNumber(
919 std::min(cur_version, kCompatibleVersionNumber));
920 transaction.Commit();
921 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
922 base::TimeTicks::Now() - start_time);
925 if (cur_version == 6) {
926 const base::TimeTicks start_time = base::TimeTicks::Now();
927 sql::Transaction transaction(db_.get());
928 if (!transaction.Begin())
929 return false;
930 // Alter the table to add empty "encrypted value" column.
931 if (!db_->Execute("ALTER TABLE cookies "
932 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
933 LOG(WARNING) << "Unable to update cookie database to version 7.";
934 return false;
936 ++cur_version;
937 meta_table_.SetVersionNumber(cur_version);
938 meta_table_.SetCompatibleVersionNumber(
939 std::min(cur_version, kCompatibleVersionNumber));
940 transaction.Commit();
941 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
942 base::TimeTicks::Now() - start_time);
945 if (cur_version == 7) {
946 const base::TimeTicks start_time = base::TimeTicks::Now();
947 sql::Transaction transaction(db_.get());
948 if (!transaction.Begin())
949 return false;
950 // Alter the table to add a 'firstpartyonly' column.
951 if (!db_->Execute(
952 "ALTER TABLE cookies "
953 "ADD COLUMN firstpartyonly INTEGER DEFAULT 0")) {
954 LOG(WARNING) << "Unable to update cookie database to version 8.";
955 return false;
957 ++cur_version;
958 meta_table_.SetVersionNumber(cur_version);
959 meta_table_.SetCompatibleVersionNumber(
960 std::min(cur_version, kCompatibleVersionNumber));
961 transaction.Commit();
962 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV8",
963 base::TimeTicks::Now() - start_time);
966 if (cur_version == 8) {
967 const base::TimeTicks start_time = base::TimeTicks::Now();
968 sql::Transaction transaction(db_.get());
969 if (!transaction.Begin())
970 return false;
972 if (!db_->Execute("DROP INDEX IF EXISTS cookie_times")) {
973 LOG(WARNING)
974 << "Unable to drop table cookie_times in update to version 9.";
975 return false;
978 if (!db_->Execute(
979 "CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)")) {
980 LOG(WARNING) << "Unable to create index domain in update to version 9.";
981 return false;
984 if (!db_->Execute(
985 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent) "
986 "where persistent != 1")) {
987 LOG(WARNING)
988 << "Unable to create index is_transient in update to version 9.";
989 return false;
991 ++cur_version;
992 meta_table_.SetVersionNumber(cur_version);
993 meta_table_.SetCompatibleVersionNumber(
994 std::min(cur_version, kCompatibleVersionNumber));
995 transaction.Commit();
996 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV9",
997 base::TimeTicks::Now() - start_time);
1000 // Put future migration cases here.
1002 if (cur_version < kCurrentVersionNumber) {
1003 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
1005 meta_table_.Reset();
1006 db_.reset(new sql::Connection);
1007 if (!sql::Connection::Delete(path_) ||
1008 !db_->Open(path_) ||
1009 !meta_table_.Init(
1010 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
1011 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
1012 NOTREACHED() << "Unable to reset the cookie DB.";
1013 meta_table_.Reset();
1014 db_.reset();
1015 return false;
1019 return true;
1022 void SQLitePersistentCookieStore::Backend::AddCookie(
1023 const net::CanonicalCookie& cc) {
1024 BatchOperation(PendingOperation::COOKIE_ADD, cc);
1027 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1028 const net::CanonicalCookie& cc) {
1029 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1032 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1033 const net::CanonicalCookie& cc) {
1034 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1037 void SQLitePersistentCookieStore::Backend::BatchOperation(
1038 PendingOperation::OperationType op,
1039 const net::CanonicalCookie& cc) {
1040 // Commit every 30 seconds.
1041 static const int kCommitIntervalMs = 30 * 1000;
1042 // Commit right away if we have more than 512 outstanding operations.
1043 static const size_t kCommitAfterBatchSize = 512;
1044 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1046 // We do a full copy of the cookie here, and hopefully just here.
1047 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1049 PendingOperationsList::size_type num_pending;
1051 base::AutoLock locked(lock_);
1052 pending_.push_back(po.release());
1053 num_pending = ++num_pending_;
1056 if (num_pending == 1) {
1057 // We've gotten our first entry for this batch, fire off the timer.
1058 if (!background_task_runner_->PostDelayedTask(
1059 FROM_HERE, base::Bind(&Backend::Commit, this),
1060 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
1061 NOTREACHED() << "background_task_runner_ is not running.";
1063 } else if (num_pending == kCommitAfterBatchSize) {
1064 // We've reached a big enough batch, fire off a commit now.
1065 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1069 void SQLitePersistentCookieStore::Backend::Commit() {
1070 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1072 PendingOperationsList ops;
1074 base::AutoLock locked(lock_);
1075 pending_.swap(ops);
1076 num_pending_ = 0;
1079 // Maybe an old timer fired or we are already Close()'ed.
1080 if (!db_.get() || ops.empty())
1081 return;
1083 sql::Statement add_smt(db_->GetCachedStatement(
1084 SQL_FROM_HERE,
1085 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1086 "encrypted_value, path, expires_utc, secure, httponly, firstpartyonly, "
1087 "last_access_utc, has_expires, persistent, priority) "
1088 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1089 if (!add_smt.is_valid())
1090 return;
1092 sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1093 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1094 if (!update_access_smt.is_valid())
1095 return;
1097 sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1098 "DELETE FROM cookies WHERE creation_utc=?"));
1099 if (!del_smt.is_valid())
1100 return;
1102 sql::Transaction transaction(db_.get());
1103 if (!transaction.Begin())
1104 return;
1106 for (PendingOperationsList::iterator it = ops.begin();
1107 it != ops.end(); ++it) {
1108 // Free the cookies as we commit them to the database.
1109 scoped_ptr<PendingOperation> po(*it);
1110 switch (po->op()) {
1111 case PendingOperation::COOKIE_ADD:
1112 cookies_per_origin_[
1113 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
1114 add_smt.Reset(true);
1115 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1116 add_smt.BindString(1, po->cc().Domain());
1117 add_smt.BindString(2, po->cc().Name());
1118 if (crypto_) {
1119 std::string encrypted_value;
1120 add_smt.BindCString(3, ""); // value
1121 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1122 // BindBlob() immediately makes an internal copy of the data.
1123 add_smt.BindBlob(4, encrypted_value.data(),
1124 static_cast<int>(encrypted_value.length()));
1125 } else {
1126 add_smt.BindString(3, po->cc().Value());
1127 add_smt.BindBlob(4, "", 0); // encrypted_value
1129 add_smt.BindString(5, po->cc().Path());
1130 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1131 add_smt.BindInt(7, po->cc().IsSecure());
1132 add_smt.BindInt(8, po->cc().IsHttpOnly());
1133 add_smt.BindInt(9, po->cc().IsFirstPartyOnly());
1134 add_smt.BindInt64(10, po->cc().LastAccessDate().ToInternalValue());
1135 add_smt.BindInt(11, po->cc().IsPersistent());
1136 add_smt.BindInt(12, po->cc().IsPersistent());
1137 add_smt.BindInt(13,
1138 CookiePriorityToDBCookiePriority(po->cc().Priority()));
1139 if (!add_smt.Run())
1140 NOTREACHED() << "Could not add a cookie to the DB.";
1141 break;
1143 case PendingOperation::COOKIE_UPDATEACCESS:
1144 update_access_smt.Reset(true);
1145 update_access_smt.BindInt64(0,
1146 po->cc().LastAccessDate().ToInternalValue());
1147 update_access_smt.BindInt64(1,
1148 po->cc().CreationDate().ToInternalValue());
1149 if (!update_access_smt.Run())
1150 NOTREACHED() << "Could not update cookie last access time in the DB.";
1151 break;
1153 case PendingOperation::COOKIE_DELETE:
1154 cookies_per_origin_[
1155 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1156 del_smt.Reset(true);
1157 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1158 if (!del_smt.Run())
1159 NOTREACHED() << "Could not delete a cookie from the DB.";
1160 break;
1162 default:
1163 NOTREACHED();
1164 break;
1167 bool succeeded = transaction.Commit();
1168 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1169 succeeded ? 0 : 1, 2);
1172 void SQLitePersistentCookieStore::Backend::Flush(
1173 const base::Closure& callback) {
1174 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1175 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1177 if (!callback.is_null()) {
1178 // We want the completion task to run immediately after Commit() returns.
1179 // Posting it from here means there is less chance of another task getting
1180 // onto the message queue first, than if we posted it from Commit() itself.
1181 PostBackgroundTask(FROM_HERE, callback);
1185 // Fire off a close message to the background runner. We could still have a
1186 // pending commit timer or Load operations holding references on us, but if/when
1187 // this fires we will already have been cleaned up and it will be ignored.
1188 void SQLitePersistentCookieStore::Backend::Close() {
1189 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1190 InternalBackgroundClose();
1191 } else {
1192 // Must close the backend on the background runner.
1193 PostBackgroundTask(FROM_HERE,
1194 base::Bind(&Backend::InternalBackgroundClose, this));
1198 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1199 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1200 // Commit any pending operations
1201 Commit();
1203 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1204 special_storage_policy_->HasSessionOnlyOrigins()) {
1205 DeleteSessionCookiesOnShutdown();
1208 meta_table_.Reset();
1209 db_.reset();
1212 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1213 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1215 if (!db_)
1216 return;
1218 if (!special_storage_policy_.get())
1219 return;
1221 sql::Statement del_smt(db_->GetCachedStatement(
1222 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1223 if (!del_smt.is_valid()) {
1224 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1225 return;
1228 sql::Transaction transaction(db_.get());
1229 if (!transaction.Begin()) {
1230 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1231 return;
1234 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1235 it != cookies_per_origin_.end(); ++it) {
1236 if (it->second <= 0) {
1237 DCHECK_EQ(0, it->second);
1238 continue;
1240 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1241 it->first.second));
1242 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1243 continue;
1245 del_smt.Reset(true);
1246 del_smt.BindString(0, it->first.first);
1247 del_smt.BindInt(1, it->first.second);
1248 if (!del_smt.Run())
1249 NOTREACHED() << "Could not delete a cookie from the DB.";
1252 if (!transaction.Commit())
1253 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1256 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1257 int error,
1258 sql::Statement* stmt) {
1259 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1261 if (!sql::IsErrorCatastrophic(error))
1262 return;
1264 // TODO(shess): Running KillDatabase() multiple times should be
1265 // safe.
1266 if (corruption_detected_)
1267 return;
1269 corruption_detected_ = true;
1271 // Don't just do the close/delete here, as we are being called by |db| and
1272 // that seems dangerous.
1273 // TODO(shess): Consider just calling RazeAndClose() immediately.
1274 // db_ may not be safe to reset at this point, but RazeAndClose()
1275 // would cause the stack to unwind safely with errors.
1276 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1279 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1280 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1282 if (db_) {
1283 // This Backend will now be in-memory only. In a future run we will recreate
1284 // the database. Hopefully things go better then!
1285 bool success = db_->RazeAndClose();
1286 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1287 meta_table_.Reset();
1288 db_.reset();
1292 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1293 base::AutoLock locked(lock_);
1294 force_keep_session_state_ = true;
1297 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1298 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1299 if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0"))
1300 LOG(WARNING) << "Unable to delete session cookies.";
1303 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1304 const tracked_objects::Location& origin, const base::Closure& task) {
1305 if (!background_task_runner_->PostTask(origin, task)) {
1306 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1307 << " to background_task_runner_.";
1311 void SQLitePersistentCookieStore::Backend::PostClientTask(
1312 const tracked_objects::Location& origin, const base::Closure& task) {
1313 if (!client_task_runner_->PostTask(origin, task)) {
1314 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1315 << " to client_task_runner_.";
1319 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1320 const LoadedCallback& loaded_callback,
1321 bool success) {
1322 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1323 loaded_callback, success));
1324 if (success && !restore_old_session_cookies_)
1325 DeleteSessionCookiesOnStartup();
1328 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1329 const base::FilePath& path,
1330 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1331 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1332 bool restore_old_session_cookies,
1333 storage::SpecialStoragePolicy* special_storage_policy,
1334 net::CookieCryptoDelegate* crypto_delegate)
1335 : backend_(new Backend(path,
1336 client_task_runner,
1337 background_task_runner,
1338 restore_old_session_cookies,
1339 special_storage_policy,
1340 crypto_delegate)) {
1343 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1344 backend_->Load(loaded_callback);
1347 void SQLitePersistentCookieStore::LoadCookiesForKey(
1348 const std::string& key,
1349 const LoadedCallback& loaded_callback) {
1350 backend_->LoadCookiesForKey(key, loaded_callback);
1353 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) {
1354 backend_->AddCookie(cc);
1357 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1358 const net::CanonicalCookie& cc) {
1359 backend_->UpdateCookieAccessTime(cc);
1362 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) {
1363 backend_->DeleteCookie(cc);
1366 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1367 backend_->SetForceKeepSessionState();
1370 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1371 backend_->Flush(callback);
1374 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1375 backend_->Close();
1376 // We release our reference to the Backend, though it will probably still have
1377 // a reference if the background runner has not run Close() yet.
1380 CookieStoreConfig::CookieStoreConfig()
1381 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1382 crypto_delegate(NULL) {
1383 // Default to an in-memory cookie store.
1386 CookieStoreConfig::CookieStoreConfig(
1387 const base::FilePath& path,
1388 SessionCookieMode session_cookie_mode,
1389 storage::SpecialStoragePolicy* storage_policy,
1390 net::CookieMonsterDelegate* cookie_delegate)
1391 : path(path),
1392 session_cookie_mode(session_cookie_mode),
1393 storage_policy(storage_policy),
1394 cookie_delegate(cookie_delegate),
1395 crypto_delegate(NULL) {
1396 CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1399 CookieStoreConfig::~CookieStoreConfig() {
1402 net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1403 net::CookieMonster* cookie_monster = NULL;
1405 if (config.path.empty()) {
1406 // Empty path means in-memory store.
1407 cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate.get());
1408 } else {
1409 scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1410 config.client_task_runner;
1411 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1412 config.background_task_runner;
1414 if (!client_task_runner.get()) {
1415 client_task_runner =
1416 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1419 if (!background_task_runner.get()) {
1420 background_task_runner =
1421 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1422 BrowserThread::GetBlockingPool()->GetSequenceToken());
1425 SQLitePersistentCookieStore* persistent_store =
1426 new SQLitePersistentCookieStore(
1427 config.path,
1428 client_task_runner,
1429 background_task_runner,
1430 (config.session_cookie_mode ==
1431 CookieStoreConfig::RESTORED_SESSION_COOKIES),
1432 config.storage_policy.get(),
1433 config.crypto_delegate);
1435 cookie_monster =
1436 new net::CookieMonster(persistent_store, config.cookie_delegate.get());
1437 if ((config.session_cookie_mode ==
1438 CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1439 (config.session_cookie_mode ==
1440 CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1441 cookie_monster->SetPersistSessionCookies(true);
1445 return cookie_monster;
1448 } // namespace content