Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / extras / sqlite / sqlite_persistent_cookie_store.cc
blob8a063d004f4ae41e948136eacc0caccf00513777
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/histogram_macros.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/sequenced_task_runner.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/synchronization/lock.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "base/time/time.h"
27 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
28 #include "net/cookies/canonical_cookie.h"
29 #include "net/cookies/cookie_constants.h"
30 #include "net/cookies/cookie_util.h"
31 #include "net/extras/sqlite/cookie_crypto_delegate.h"
32 #include "sql/error_delegate_util.h"
33 #include "sql/meta_table.h"
34 #include "sql/statement.h"
35 #include "sql/transaction.h"
36 #include "url/gurl.h"
38 using base::Time;
40 namespace {
42 // The persistent cookie store is loaded into memory on eTLD at a time. This
43 // variable controls the delay between loading eTLDs, so as to not overload the
44 // CPU or I/O with these low priority requests immediately after start up.
45 const int kLoadDelayMilliseconds = 0;
47 } // namespace
49 namespace net {
51 // This class is designed to be shared between any client thread and the
52 // background task runner. It batches operations and commits them on a timer.
54 // SQLitePersistentCookieStore::Load is called to load all cookies. It
55 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
56 // task to the background runner. This task calls Backend::ChainLoadCookies(),
57 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
58 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
59 // posted to the client runner, which notifies the caller of
60 // SQLitePersistentCookieStore::Load that the load is complete.
62 // If a priority load request is invoked via SQLitePersistentCookieStore::
63 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
64 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
65 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
66 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
67 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
69 // Subsequent to loading, mutations may be queued by any thread using
70 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
71 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
72 // whichever occurs first.
73 class SQLitePersistentCookieStore::Backend
74 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
75 public:
76 Backend(
77 const base::FilePath& path,
78 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
79 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
80 bool restore_old_session_cookies,
81 CookieCryptoDelegate* crypto_delegate)
82 : path_(path),
83 num_pending_(0),
84 initialized_(false),
85 corruption_detected_(false),
86 restore_old_session_cookies_(restore_old_session_cookies),
87 num_cookies_read_(0),
88 client_task_runner_(client_task_runner),
89 background_task_runner_(background_task_runner),
90 num_priority_waiting_(0),
91 total_priority_requests_(0),
92 crypto_(crypto_delegate) {}
94 // Creates or loads the SQLite database.
95 void Load(const LoadedCallback& loaded_callback);
97 // Loads cookies for the domain key (eTLD+1).
98 void LoadCookiesForKey(const std::string& domain,
99 const LoadedCallback& loaded_callback);
101 // Steps through all results of |smt|, makes a cookie from each, and adds the
102 // cookie to |cookies|. This method also updates |num_cookies_read_|.
103 void MakeCookiesFromSQLStatement(std::vector<CanonicalCookie*>* cookies,
104 sql::Statement* statement);
106 // Batch a cookie addition.
107 void AddCookie(const CanonicalCookie& cc);
109 // Batch a cookie access time update.
110 void UpdateCookieAccessTime(const CanonicalCookie& cc);
112 // Batch a cookie deletion.
113 void DeleteCookie(const CanonicalCookie& cc);
115 // Commit pending operations as soon as possible.
116 void Flush(const base::Closure& callback);
118 // Commit any pending operations and close the database. This must be called
119 // before the object is destructed.
120 void Close(const base::Closure& callback);
122 // Post background delete of all cookies that match |cookies|.
123 void DeleteAllInList(const std::list<CookieOrigin>& cookies);
125 private:
126 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
128 // You should call Close() before destructing this object.
129 ~Backend() {
130 DCHECK(!db_.get()) << "Close should have already been called.";
131 DCHECK_EQ(0u, num_pending_);
132 DCHECK(pending_.empty());
134 for (CanonicalCookie* cookie : cookies_) {
135 delete cookie;
139 // Database upgrade statements.
140 bool EnsureDatabaseVersion();
142 class PendingOperation {
143 public:
144 enum OperationType {
145 COOKIE_ADD,
146 COOKIE_UPDATEACCESS,
147 COOKIE_DELETE,
150 PendingOperation(OperationType op, const CanonicalCookie& cc)
151 : op_(op), cc_(cc) {}
153 OperationType op() const { return op_; }
154 const CanonicalCookie& cc() const { return cc_; }
156 private:
157 OperationType op_;
158 CanonicalCookie cc_;
161 private:
162 // Creates or loads the SQLite database on background runner.
163 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
164 const base::Time& posted_at);
166 // Loads cookies for the domain key (eTLD+1) on background runner.
167 void LoadKeyAndNotifyInBackground(const std::string& domains,
168 const LoadedCallback& loaded_callback,
169 const base::Time& posted_at);
171 // Notifies the CookieMonster when loading completes for a specific domain key
172 // or for all domain keys. Triggers the callback and passes it all cookies
173 // that have been loaded from DB since last IO notification.
174 void Notify(const LoadedCallback& loaded_callback, bool load_success);
176 // Sends notification when the entire store is loaded, and reports metrics
177 // for the total time to load and aggregated results from any priority loads
178 // that occurred.
179 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
180 bool load_success);
182 // Sends notification when a single priority load completes. Updates priority
183 // load metric data. The data is sent only after the final load completes.
184 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
185 bool load_success,
186 const base::Time& requested_at);
188 // Sends all metrics, including posting a ReportMetricsInBackground task.
189 // Called after all priority and regular loading is complete.
190 void ReportMetrics();
192 // Sends background-runner owned metrics (i.e., the combined duration of all
193 // BG-runner tasks).
194 void ReportMetricsInBackground();
196 // Initialize the data base.
197 bool InitializeDatabase();
199 // Loads cookies for the next domain key from the DB, then either reschedules
200 // itself or schedules the provided callback to run on the client runner (if
201 // all domains are loaded).
202 void ChainLoadCookies(const LoadedCallback& loaded_callback);
204 // Load all cookies for a set of domains/hosts
205 bool LoadCookiesForDomains(const std::set<std::string>& key);
207 // Batch a cookie operation (add or delete)
208 void BatchOperation(PendingOperation::OperationType op,
209 const CanonicalCookie& cc);
210 // Commit our pending operations to the database.
211 void Commit();
212 // Close() executed on the background runner.
213 void InternalBackgroundClose(const base::Closure& callback);
215 void DeleteSessionCookiesOnStartup();
217 void BackgroundDeleteAllInList(const std::list<CookieOrigin>& cookies);
219 void DatabaseErrorCallback(int error, sql::Statement* stmt);
220 void KillDatabase();
222 void PostBackgroundTask(const tracked_objects::Location& origin,
223 const base::Closure& task);
224 void PostClientTask(const tracked_objects::Location& origin,
225 const base::Closure& task);
227 // Shared code between the different load strategies to be used after all
228 // cookies have been loaded.
229 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
230 bool success);
232 const base::FilePath path_;
233 scoped_ptr<sql::Connection> db_;
234 sql::MetaTable meta_table_;
236 typedef std::list<PendingOperation*> PendingOperationsList;
237 PendingOperationsList pending_;
238 PendingOperationsList::size_type num_pending_;
239 // Guard |cookies_|, |pending_|, |num_pending_|.
240 base::Lock lock_;
242 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
243 // the number of messages sent to the client runner. Sent back in response to
244 // individual load requests for domain keys or when all loading completes.
245 // Ownership of the cookies in this vector is transferred to the client in
246 // response to individual load requests or when all loading completes.
247 std::vector<CanonicalCookie*> cookies_;
249 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
250 std::map<std::string, std::set<std::string>> keys_to_load_;
252 // Indicates if DB has been initialized.
253 bool initialized_;
255 // Indicates if the kill-database callback has been scheduled.
256 bool corruption_detected_;
258 // If false, we should filter out session cookies when reading the DB.
259 bool restore_old_session_cookies_;
261 // The cumulative time spent loading the cookies on the background runner.
262 // Incremented and reported from the background runner.
263 base::TimeDelta cookie_load_duration_;
265 // The total number of cookies read. Incremented and reported on the
266 // background runner.
267 int num_cookies_read_;
269 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
270 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
272 // Guards the following metrics-related properties (only accessed when
273 // starting/completing priority loads or completing the total load).
274 base::Lock metrics_lock_;
275 int num_priority_waiting_;
276 // The total number of priority requests.
277 int total_priority_requests_;
278 // The time when |num_priority_waiting_| incremented to 1.
279 base::Time current_priority_wait_start_;
280 // The cumulative duration of time when |num_priority_waiting_| was greater
281 // than 1.
282 base::TimeDelta priority_wait_duration_;
283 // Class with functions that do cryptographic operations (for protecting
284 // cookies stored persistently).
286 // Not owned.
287 CookieCryptoDelegate* crypto_;
289 DISALLOW_COPY_AND_ASSIGN(Backend);
292 namespace {
294 // Version number of the database.
296 // Version 9 adds a partial index to track non-persistent cookies.
297 // Non-persistent cookies sometimes need to be deleted on startup. There are
298 // frequently few or no non-persistent cookies, so the partial index allows the
299 // deletion to be sped up or skipped, without having to page in the DB.
301 // Version 8 adds "first-party only" cookies.
303 // Version 7 adds encrypted values. Old values will continue to be used but
304 // all new values written will be encrypted on selected operating systems. New
305 // records read by old clients will simply get an empty cookie value while old
306 // records read by new clients will continue to operate with the unencrypted
307 // version. New and old clients alike will always write/update records with
308 // what they support.
310 // Version 6 adds cookie priorities. This allows developers to influence the
311 // order in which cookies are evicted in order to meet domain cookie limits.
313 // Version 5 adds the columns has_expires and is_persistent, so that the
314 // database can store session cookies as well as persistent cookies. Databases
315 // of version 5 are incompatible with older versions of code. If a database of
316 // version 5 is read by older code, session cookies will be treated as normal
317 // cookies. Currently, these fields are written, but not read anymore.
319 // In version 4, we migrated the time epoch. If you open the DB with an older
320 // version on Mac or Linux, the times will look wonky, but the file will likely
321 // be usable. On Windows version 3 and 4 are the same.
323 // Version 3 updated the database to include the last access time, so we can
324 // expire them in decreasing order of use when we've reached the maximum
325 // number of cookies.
326 const int kCurrentVersionNumber = 9;
327 const int kCompatibleVersionNumber = 5;
329 // Possible values for the 'priority' column.
330 enum DBCookiePriority {
331 kCookiePriorityLow = 0,
332 kCookiePriorityMedium = 1,
333 kCookiePriorityHigh = 2,
336 DBCookiePriority CookiePriorityToDBCookiePriority(CookiePriority value) {
337 switch (value) {
338 case COOKIE_PRIORITY_LOW:
339 return kCookiePriorityLow;
340 case COOKIE_PRIORITY_MEDIUM:
341 return kCookiePriorityMedium;
342 case COOKIE_PRIORITY_HIGH:
343 return kCookiePriorityHigh;
346 NOTREACHED();
347 return kCookiePriorityMedium;
350 CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
351 switch (value) {
352 case kCookiePriorityLow:
353 return COOKIE_PRIORITY_LOW;
354 case kCookiePriorityMedium:
355 return COOKIE_PRIORITY_MEDIUM;
356 case kCookiePriorityHigh:
357 return COOKIE_PRIORITY_HIGH;
360 NOTREACHED();
361 return COOKIE_PRIORITY_DEFAULT;
364 // Increments a specified TimeDelta by the duration between this object's
365 // constructor and destructor. Not thread safe. Multiple instances may be
366 // created with the same delta instance as long as their lifetimes are nested.
367 // The shortest lived instances have no impact.
368 class IncrementTimeDelta {
369 public:
370 explicit IncrementTimeDelta(base::TimeDelta* delta)
371 : delta_(delta), original_value_(*delta), start_(base::Time::Now()) {}
373 ~IncrementTimeDelta() {
374 *delta_ = original_value_ + base::Time::Now() - start_;
377 private:
378 base::TimeDelta* delta_;
379 base::TimeDelta original_value_;
380 base::Time start_;
382 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
385 // Initializes the cookies table, returning true on success.
386 bool InitTable(sql::Connection* db) {
387 if (db->DoesTableExist("cookies"))
388 return true;
390 std::string stmt(base::StringPrintf(
391 "CREATE TABLE cookies ("
392 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
393 "host_key TEXT NOT NULL,"
394 "name TEXT NOT NULL,"
395 "value TEXT NOT NULL,"
396 "path TEXT NOT NULL,"
397 "expires_utc INTEGER NOT NULL,"
398 "secure INTEGER NOT NULL,"
399 "httponly INTEGER NOT NULL,"
400 "last_access_utc INTEGER NOT NULL, "
401 "has_expires INTEGER NOT NULL DEFAULT 1, "
402 "persistent INTEGER NOT NULL DEFAULT 1,"
403 "priority INTEGER NOT NULL DEFAULT %d,"
404 "encrypted_value BLOB DEFAULT '',"
405 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
406 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
407 if (!db->Execute(stmt.c_str()))
408 return false;
410 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)"))
411 return false;
413 #if defined(OS_IOS)
414 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
415 // partial indices.
416 if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) {
417 #else
418 if (!db->Execute(
419 "CREATE INDEX is_transient ON cookies(persistent) "
420 "where persistent != 1")) {
421 #endif
422 return false;
425 return true;
428 } // namespace
430 void SQLitePersistentCookieStore::Backend::Load(
431 const LoadedCallback& loaded_callback) {
432 PostBackgroundTask(FROM_HERE,
433 base::Bind(&Backend::LoadAndNotifyInBackground, this,
434 loaded_callback, base::Time::Now()));
437 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
438 const std::string& key,
439 const LoadedCallback& loaded_callback) {
441 base::AutoLock locked(metrics_lock_);
442 if (num_priority_waiting_ == 0)
443 current_priority_wait_start_ = base::Time::Now();
444 num_priority_waiting_++;
445 total_priority_requests_++;
448 PostBackgroundTask(
449 FROM_HERE, base::Bind(&Backend::LoadKeyAndNotifyInBackground, this, key,
450 loaded_callback, base::Time::Now()));
453 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
454 const LoadedCallback& loaded_callback,
455 const base::Time& posted_at) {
456 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
457 IncrementTimeDelta increment(&cookie_load_duration_);
459 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoadDBQueueWait",
460 base::Time::Now() - posted_at,
461 base::TimeDelta::FromMilliseconds(1),
462 base::TimeDelta::FromMinutes(1), 50);
464 if (!InitializeDatabase()) {
465 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground,
466 this, loaded_callback, false));
467 } else {
468 ChainLoadCookies(loaded_callback);
472 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
473 const std::string& key,
474 const LoadedCallback& loaded_callback,
475 const base::Time& posted_at) {
476 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
477 IncrementTimeDelta increment(&cookie_load_duration_);
479 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeKeyLoadDBQueueWait",
480 base::Time::Now() - posted_at,
481 base::TimeDelta::FromMilliseconds(1),
482 base::TimeDelta::FromMinutes(1), 50);
484 bool success = false;
485 if (InitializeDatabase()) {
486 std::map<std::string, std::set<std::string>>::iterator it =
487 keys_to_load_.find(key);
488 if (it != keys_to_load_.end()) {
489 success = LoadCookiesForDomains(it->second);
490 keys_to_load_.erase(it);
491 } else {
492 success = true;
496 PostClientTask(
497 FROM_HERE,
498 base::Bind(
499 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
500 this, loaded_callback, success, posted_at));
503 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
504 const LoadedCallback& loaded_callback,
505 bool load_success,
506 const ::Time& requested_at) {
507 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
509 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeKeyLoadTotalWait",
510 base::Time::Now() - requested_at,
511 base::TimeDelta::FromMilliseconds(1),
512 base::TimeDelta::FromMinutes(1), 50);
514 Notify(loaded_callback, load_success);
517 base::AutoLock locked(metrics_lock_);
518 num_priority_waiting_--;
519 if (num_priority_waiting_ == 0) {
520 priority_wait_duration_ +=
521 base::Time::Now() - current_priority_wait_start_;
526 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
527 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoad", cookie_load_duration_,
528 base::TimeDelta::FromMilliseconds(1),
529 base::TimeDelta::FromMinutes(1), 50);
532 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
533 PostBackgroundTask(
534 FROM_HERE,
535 base::Bind(
536 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground,
537 this));
540 base::AutoLock locked(metrics_lock_);
541 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.PriorityBlockingTime",
542 priority_wait_duration_,
543 base::TimeDelta::FromMilliseconds(1),
544 base::TimeDelta::FromMinutes(1), 50);
546 UMA_HISTOGRAM_COUNTS_100("Cookie.PriorityLoadCount",
547 total_priority_requests_);
549 UMA_HISTOGRAM_COUNTS_10000("Cookie.NumberOfLoadedCookies",
550 num_cookies_read_);
554 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
555 const LoadedCallback& loaded_callback,
556 bool load_success) {
557 Notify(loaded_callback, load_success);
559 if (load_success)
560 ReportMetrics();
563 void SQLitePersistentCookieStore::Backend::Notify(
564 const LoadedCallback& loaded_callback,
565 bool load_success) {
566 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
568 std::vector<CanonicalCookie*> cookies;
570 base::AutoLock locked(lock_);
571 cookies.swap(cookies_);
574 loaded_callback.Run(cookies);
577 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
578 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
580 if (initialized_ || corruption_detected_) {
581 // Return false if we were previously initialized but the DB has since been
582 // closed, or if corruption caused a database reset during initialization.
583 return db_ != NULL;
586 base::Time start = base::Time::Now();
588 const base::FilePath dir = path_.DirName();
589 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
590 return false;
593 int64 db_size = 0;
594 if (base::GetFileSize(path_, &db_size))
595 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024);
597 db_.reset(new sql::Connection);
598 db_->set_histogram_tag("Cookie");
600 // Unretained to avoid a ref loop with |db_|.
601 db_->set_error_callback(
602 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
603 base::Unretained(this)));
605 if (!db_->Open(path_)) {
606 NOTREACHED() << "Unable to open cookie DB.";
607 if (corruption_detected_)
608 db_->Raze();
609 meta_table_.Reset();
610 db_.reset();
611 return false;
614 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
615 NOTREACHED() << "Unable to open cookie DB.";
616 if (corruption_detected_)
617 db_->Raze();
618 meta_table_.Reset();
619 db_.reset();
620 return false;
623 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeInitializeDB",
624 base::Time::Now() - start,
625 base::TimeDelta::FromMilliseconds(1),
626 base::TimeDelta::FromMinutes(1), 50);
628 start = base::Time::Now();
630 // Retrieve all the domains
631 sql::Statement smt(
632 db_->GetUniqueStatement("SELECT DISTINCT host_key FROM cookies"));
634 if (!smt.is_valid()) {
635 if (corruption_detected_)
636 db_->Raze();
637 meta_table_.Reset();
638 db_.reset();
639 return false;
642 std::vector<std::string> host_keys;
643 while (smt.Step())
644 host_keys.push_back(smt.ColumnString(0));
646 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeLoadDomains",
647 base::Time::Now() - start,
648 base::TimeDelta::FromMilliseconds(1),
649 base::TimeDelta::FromMinutes(1), 50);
651 base::Time start_parse = base::Time::Now();
653 // Build a map of domain keys (always eTLD+1) to domains.
654 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
655 const std::string& domain = host_keys[idx];
656 std::string key = registry_controlled_domains::GetDomainAndRegistry(
657 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
659 keys_to_load_[key].insert(domain);
662 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeParseDomains",
663 base::Time::Now() - start_parse,
664 base::TimeDelta::FromMilliseconds(1),
665 base::TimeDelta::FromMinutes(1), 50);
667 UMA_HISTOGRAM_CUSTOM_TIMES("Cookie.TimeInitializeDomainMap",
668 base::Time::Now() - start,
669 base::TimeDelta::FromMilliseconds(1),
670 base::TimeDelta::FromMinutes(1), 50);
672 initialized_ = true;
674 if (!restore_old_session_cookies_)
675 DeleteSessionCookiesOnStartup();
676 return true;
679 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
680 const LoadedCallback& loaded_callback) {
681 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
682 IncrementTimeDelta increment(&cookie_load_duration_);
684 bool load_success = true;
686 if (!db_) {
687 // Close() has been called on this store.
688 load_success = false;
689 } else if (keys_to_load_.size() > 0) {
690 // Load cookies for the first domain key.
691 std::map<std::string, std::set<std::string>>::iterator it =
692 keys_to_load_.begin();
693 load_success = LoadCookiesForDomains(it->second);
694 keys_to_load_.erase(it);
697 // If load is successful and there are more domain keys to be loaded,
698 // then post a background task to continue chain-load;
699 // Otherwise notify on client runner.
700 if (load_success && keys_to_load_.size() > 0) {
701 bool success = background_task_runner_->PostDelayedTask(
702 FROM_HERE,
703 base::Bind(&Backend::ChainLoadCookies, this, loaded_callback),
704 base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds));
705 if (!success) {
706 LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
707 << " to background_task_runner_.";
709 } else {
710 FinishedLoadingCookies(loaded_callback, load_success);
714 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
715 const std::set<std::string>& domains) {
716 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
718 sql::Statement smt;
719 if (restore_old_session_cookies_) {
720 smt.Assign(db_->GetCachedStatement(
721 SQL_FROM_HERE,
722 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
723 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
724 "has_expires, persistent, priority FROM cookies WHERE host_key = ?"));
725 } else {
726 smt.Assign(db_->GetCachedStatement(
727 SQL_FROM_HERE,
728 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
729 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
730 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
731 "AND persistent = 1"));
733 if (!smt.is_valid()) {
734 smt.Clear(); // Disconnect smt_ref from db_.
735 meta_table_.Reset();
736 db_.reset();
737 return false;
740 std::vector<CanonicalCookie*> cookies;
741 std::set<std::string>::const_iterator it = domains.begin();
742 for (; it != domains.end(); ++it) {
743 smt.BindString(0, *it);
744 MakeCookiesFromSQLStatement(&cookies, &smt);
745 smt.Reset(true);
748 base::AutoLock locked(lock_);
749 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
751 return true;
754 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
755 std::vector<CanonicalCookie*>* cookies,
756 sql::Statement* statement) {
757 sql::Statement& smt = *statement;
758 while (smt.Step()) {
759 std::string value;
760 std::string encrypted_value = smt.ColumnString(4);
761 if (!encrypted_value.empty() && crypto_) {
762 if (!crypto_->DecryptString(encrypted_value, &value))
763 continue;
764 } else {
765 value = smt.ColumnString(3);
767 scoped_ptr<CanonicalCookie> cc(new CanonicalCookie(
768 // The "source" URL is not used with persisted cookies.
769 GURL(), // Source
770 smt.ColumnString(2), // name
771 value, // value
772 smt.ColumnString(1), // domain
773 smt.ColumnString(5), // path
774 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
775 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
776 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
777 smt.ColumnInt(7) != 0, // secure
778 smt.ColumnInt(8) != 0, // httponly
779 smt.ColumnInt(9) != 0, // firstpartyonly
780 DBCookiePriorityToCookiePriority(
781 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
782 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
783 << L"CreationDate too recent";
784 cookies->push_back(cc.release());
785 ++num_cookies_read_;
789 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
790 // Version check.
791 if (!meta_table_.Init(db_.get(), kCurrentVersionNumber,
792 kCompatibleVersionNumber)) {
793 return false;
796 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
797 LOG(WARNING) << "Cookie database is too new.";
798 return false;
801 int cur_version = meta_table_.GetVersionNumber();
802 if (cur_version == 2) {
803 sql::Transaction transaction(db_.get());
804 if (!transaction.Begin())
805 return false;
806 if (!db_->Execute(
807 "ALTER TABLE cookies ADD COLUMN last_access_utc "
808 "INTEGER DEFAULT 0") ||
809 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
810 LOG(WARNING) << "Unable to update cookie database to version 3.";
811 return false;
813 ++cur_version;
814 meta_table_.SetVersionNumber(cur_version);
815 meta_table_.SetCompatibleVersionNumber(
816 std::min(cur_version, kCompatibleVersionNumber));
817 transaction.Commit();
820 if (cur_version == 3) {
821 // The time epoch changed for Mac & Linux in this version to match Windows.
822 // This patch came after the main epoch change happened, so some
823 // developers have "good" times for cookies added by the more recent
824 // versions. So we have to be careful to only update times that are under
825 // the old system (which will appear to be from before 1970 in the new
826 // system). The magic number used below is 1970 in our time units.
827 sql::Transaction transaction(db_.get());
828 transaction.Begin();
829 #if !defined(OS_WIN)
830 ignore_result(db_->Execute(
831 "UPDATE cookies "
832 "SET creation_utc = creation_utc + 11644473600000000 "
833 "WHERE rowid IN "
834 "(SELECT rowid FROM cookies WHERE "
835 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
836 ignore_result(db_->Execute(
837 "UPDATE cookies "
838 "SET expires_utc = expires_utc + 11644473600000000 "
839 "WHERE rowid IN "
840 "(SELECT rowid FROM cookies WHERE "
841 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
842 ignore_result(db_->Execute(
843 "UPDATE cookies "
844 "SET last_access_utc = last_access_utc + 11644473600000000 "
845 "WHERE rowid IN "
846 "(SELECT rowid FROM cookies WHERE "
847 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
848 #endif
849 ++cur_version;
850 meta_table_.SetVersionNumber(cur_version);
851 transaction.Commit();
854 if (cur_version == 4) {
855 const base::TimeTicks start_time = base::TimeTicks::Now();
856 sql::Transaction transaction(db_.get());
857 if (!transaction.Begin())
858 return false;
859 if (!db_->Execute(
860 "ALTER TABLE cookies "
861 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
862 !db_->Execute(
863 "ALTER TABLE cookies "
864 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
865 LOG(WARNING) << "Unable to update cookie database to version 5.";
866 return false;
868 ++cur_version;
869 meta_table_.SetVersionNumber(cur_version);
870 meta_table_.SetCompatibleVersionNumber(
871 std::min(cur_version, kCompatibleVersionNumber));
872 transaction.Commit();
873 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
874 base::TimeTicks::Now() - start_time);
877 if (cur_version == 5) {
878 const base::TimeTicks start_time = base::TimeTicks::Now();
879 sql::Transaction transaction(db_.get());
880 if (!transaction.Begin())
881 return false;
882 // Alter the table to add the priority column with a default value.
883 std::string stmt(base::StringPrintf(
884 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
885 CookiePriorityToDBCookiePriority(COOKIE_PRIORITY_DEFAULT)));
886 if (!db_->Execute(stmt.c_str())) {
887 LOG(WARNING) << "Unable to update cookie database to version 6.";
888 return false;
890 ++cur_version;
891 meta_table_.SetVersionNumber(cur_version);
892 meta_table_.SetCompatibleVersionNumber(
893 std::min(cur_version, kCompatibleVersionNumber));
894 transaction.Commit();
895 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
896 base::TimeTicks::Now() - start_time);
899 if (cur_version == 6) {
900 const base::TimeTicks start_time = base::TimeTicks::Now();
901 sql::Transaction transaction(db_.get());
902 if (!transaction.Begin())
903 return false;
904 // Alter the table to add empty "encrypted value" column.
905 if (!db_->Execute(
906 "ALTER TABLE cookies "
907 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
908 LOG(WARNING) << "Unable to update cookie database to version 7.";
909 return false;
911 ++cur_version;
912 meta_table_.SetVersionNumber(cur_version);
913 meta_table_.SetCompatibleVersionNumber(
914 std::min(cur_version, kCompatibleVersionNumber));
915 transaction.Commit();
916 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
917 base::TimeTicks::Now() - start_time);
920 if (cur_version == 7) {
921 const base::TimeTicks start_time = base::TimeTicks::Now();
922 sql::Transaction transaction(db_.get());
923 if (!transaction.Begin())
924 return false;
925 // Alter the table to add a 'firstpartyonly' column.
926 if (!db_->Execute(
927 "ALTER TABLE cookies "
928 "ADD COLUMN firstpartyonly INTEGER DEFAULT 0")) {
929 LOG(WARNING) << "Unable to update cookie database to version 8.";
930 return false;
932 ++cur_version;
933 meta_table_.SetVersionNumber(cur_version);
934 meta_table_.SetCompatibleVersionNumber(
935 std::min(cur_version, kCompatibleVersionNumber));
936 transaction.Commit();
937 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV8",
938 base::TimeTicks::Now() - start_time);
941 if (cur_version == 8) {
942 const base::TimeTicks start_time = base::TimeTicks::Now();
943 sql::Transaction transaction(db_.get());
944 if (!transaction.Begin())
945 return false;
947 if (!db_->Execute("DROP INDEX IF EXISTS cookie_times")) {
948 LOG(WARNING)
949 << "Unable to drop table cookie_times in update to version 9.";
950 return false;
953 if (!db_->Execute(
954 "CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)")) {
955 LOG(WARNING) << "Unable to create index domain in update to version 9.";
956 return false;
959 #if defined(OS_IOS)
960 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
961 // partial indices.
962 if (!db_->Execute(
963 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent)")) {
964 #else
965 if (!db_->Execute(
966 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent) "
967 "where persistent != 1")) {
968 #endif
969 LOG(WARNING)
970 << "Unable to create index is_transient in update to version 9.";
971 return false;
973 ++cur_version;
974 meta_table_.SetVersionNumber(cur_version);
975 meta_table_.SetCompatibleVersionNumber(
976 std::min(cur_version, kCompatibleVersionNumber));
977 transaction.Commit();
978 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV9",
979 base::TimeTicks::Now() - start_time);
982 // Put future migration cases here.
984 if (cur_version < kCurrentVersionNumber) {
985 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
987 meta_table_.Reset();
988 db_.reset(new sql::Connection);
989 if (!sql::Connection::Delete(path_) || !db_->Open(path_) ||
990 !meta_table_.Init(db_.get(), kCurrentVersionNumber,
991 kCompatibleVersionNumber)) {
992 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
993 NOTREACHED() << "Unable to reset the cookie DB.";
994 meta_table_.Reset();
995 db_.reset();
996 return false;
1000 return true;
1003 void SQLitePersistentCookieStore::Backend::AddCookie(
1004 const CanonicalCookie& cc) {
1005 BatchOperation(PendingOperation::COOKIE_ADD, cc);
1008 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1009 const CanonicalCookie& cc) {
1010 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1013 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1014 const CanonicalCookie& cc) {
1015 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1018 void SQLitePersistentCookieStore::Backend::BatchOperation(
1019 PendingOperation::OperationType op,
1020 const CanonicalCookie& cc) {
1021 // Commit every 30 seconds.
1022 static const int kCommitIntervalMs = 30 * 1000;
1023 // Commit right away if we have more than 512 outstanding operations.
1024 static const size_t kCommitAfterBatchSize = 512;
1025 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1027 // We do a full copy of the cookie here, and hopefully just here.
1028 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1030 PendingOperationsList::size_type num_pending;
1032 base::AutoLock locked(lock_);
1033 pending_.push_back(po.release());
1034 num_pending = ++num_pending_;
1037 if (num_pending == 1) {
1038 // We've gotten our first entry for this batch, fire off the timer.
1039 if (!background_task_runner_->PostDelayedTask(
1040 FROM_HERE, base::Bind(&Backend::Commit, this),
1041 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
1042 NOTREACHED() << "background_task_runner_ is not running.";
1044 } else if (num_pending == kCommitAfterBatchSize) {
1045 // We've reached a big enough batch, fire off a commit now.
1046 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1050 void SQLitePersistentCookieStore::Backend::Commit() {
1051 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1053 PendingOperationsList ops;
1055 base::AutoLock locked(lock_);
1056 pending_.swap(ops);
1057 num_pending_ = 0;
1060 // Maybe an old timer fired or we are already Close()'ed.
1061 if (!db_.get() || ops.empty())
1062 return;
1064 sql::Statement add_smt(db_->GetCachedStatement(
1065 SQL_FROM_HERE,
1066 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1067 "encrypted_value, path, expires_utc, secure, httponly, firstpartyonly, "
1068 "last_access_utc, has_expires, persistent, priority) "
1069 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1070 if (!add_smt.is_valid())
1071 return;
1073 sql::Statement update_access_smt(db_->GetCachedStatement(
1074 SQL_FROM_HERE,
1075 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1076 if (!update_access_smt.is_valid())
1077 return;
1079 sql::Statement del_smt(db_->GetCachedStatement(
1080 SQL_FROM_HERE, "DELETE FROM cookies WHERE creation_utc=?"));
1081 if (!del_smt.is_valid())
1082 return;
1084 sql::Transaction transaction(db_.get());
1085 if (!transaction.Begin())
1086 return;
1088 for (PendingOperationsList::iterator it = ops.begin(); it != ops.end();
1089 ++it) {
1090 // Free the cookies as we commit them to the database.
1091 scoped_ptr<PendingOperation> po(*it);
1092 switch (po->op()) {
1093 case PendingOperation::COOKIE_ADD:
1094 add_smt.Reset(true);
1095 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1096 add_smt.BindString(1, po->cc().Domain());
1097 add_smt.BindString(2, po->cc().Name());
1098 if (crypto_ && crypto_->ShouldEncrypt()) {
1099 std::string encrypted_value;
1100 if (!crypto_->EncryptString(po->cc().Value(), &encrypted_value))
1101 continue;
1102 add_smt.BindCString(3, ""); // value
1103 // BindBlob() immediately makes an internal copy of the data.
1104 add_smt.BindBlob(4, encrypted_value.data(),
1105 static_cast<int>(encrypted_value.length()));
1106 } else {
1107 add_smt.BindString(3, po->cc().Value());
1108 add_smt.BindBlob(4, "", 0); // encrypted_value
1110 add_smt.BindString(5, po->cc().Path());
1111 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1112 add_smt.BindInt(7, po->cc().IsSecure());
1113 add_smt.BindInt(8, po->cc().IsHttpOnly());
1114 add_smt.BindInt(9, po->cc().IsFirstPartyOnly());
1115 add_smt.BindInt64(10, po->cc().LastAccessDate().ToInternalValue());
1116 add_smt.BindInt(11, po->cc().IsPersistent());
1117 add_smt.BindInt(12, po->cc().IsPersistent());
1118 add_smt.BindInt(13,
1119 CookiePriorityToDBCookiePriority(po->cc().Priority()));
1120 if (!add_smt.Run())
1121 NOTREACHED() << "Could not add a cookie to the DB.";
1122 break;
1124 case PendingOperation::COOKIE_UPDATEACCESS:
1125 update_access_smt.Reset(true);
1126 update_access_smt.BindInt64(
1127 0, po->cc().LastAccessDate().ToInternalValue());
1128 update_access_smt.BindInt64(1,
1129 po->cc().CreationDate().ToInternalValue());
1130 if (!update_access_smt.Run())
1131 NOTREACHED() << "Could not update cookie last access time in the DB.";
1132 break;
1134 case PendingOperation::COOKIE_DELETE:
1135 del_smt.Reset(true);
1136 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1137 if (!del_smt.Run())
1138 NOTREACHED() << "Could not delete a cookie from the DB.";
1139 break;
1141 default:
1142 NOTREACHED();
1143 break;
1146 bool succeeded = transaction.Commit();
1147 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1148 succeeded ? 0 : 1, 2);
1151 void SQLitePersistentCookieStore::Backend::Flush(
1152 const base::Closure& callback) {
1153 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1154 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1156 if (!callback.is_null()) {
1157 // We want the completion task to run immediately after Commit() returns.
1158 // Posting it from here means there is less chance of another task getting
1159 // onto the message queue first, than if we posted it from Commit() itself.
1160 PostBackgroundTask(FROM_HERE, callback);
1164 // Fire off a close message to the background runner. We could still have a
1165 // pending commit timer or Load operations holding references on us, but if/when
1166 // this fires we will already have been cleaned up and it will be ignored.
1167 void SQLitePersistentCookieStore::Backend::Close(
1168 const base::Closure& callback) {
1169 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1170 InternalBackgroundClose(callback);
1171 } else {
1172 // Must close the backend on the background runner.
1173 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::InternalBackgroundClose,
1174 this, callback));
1178 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose(
1179 const base::Closure& callback) {
1180 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1181 // Commit any pending operations
1182 Commit();
1184 meta_table_.Reset();
1185 db_.reset();
1187 // We're clean now.
1188 if (!callback.is_null())
1189 callback.Run();
1192 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1193 int error,
1194 sql::Statement* stmt) {
1195 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1197 if (!sql::IsErrorCatastrophic(error))
1198 return;
1200 // TODO(shess): Running KillDatabase() multiple times should be
1201 // safe.
1202 if (corruption_detected_)
1203 return;
1205 corruption_detected_ = true;
1207 // Don't just do the close/delete here, as we are being called by |db| and
1208 // that seems dangerous.
1209 // TODO(shess): Consider just calling RazeAndClose() immediately.
1210 // db_ may not be safe to reset at this point, but RazeAndClose()
1211 // would cause the stack to unwind safely with errors.
1212 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1215 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1216 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1218 if (db_) {
1219 // This Backend will now be in-memory only. In a future run we will recreate
1220 // the database. Hopefully things go better then!
1221 bool success = db_->RazeAndClose();
1222 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1223 meta_table_.Reset();
1224 db_.reset();
1228 void SQLitePersistentCookieStore::Backend::DeleteAllInList(
1229 const std::list<CookieOrigin>& cookies) {
1230 if (cookies.empty())
1231 return;
1233 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1234 BackgroundDeleteAllInList(cookies);
1235 } else {
1236 // Perform deletion on background task runner.
1237 PostBackgroundTask(
1238 FROM_HERE,
1239 base::Bind(&Backend::BackgroundDeleteAllInList, this, cookies));
1243 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1244 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1245 base::Time start_time = base::Time::Now();
1246 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1247 LOG(WARNING) << "Unable to delete session cookies.";
1249 UMA_HISTOGRAM_TIMES("Cookie.Startup.TimeSpentDeletingCookies",
1250 base::Time::Now() - start_time);
1251 UMA_HISTOGRAM_COUNTS("Cookie.Startup.NumberOfCookiesDeleted",
1252 db_->GetLastChangeCount());
1255 void SQLitePersistentCookieStore::Backend::BackgroundDeleteAllInList(
1256 const std::list<CookieOrigin>& cookies) {
1257 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1259 if (!db_)
1260 return;
1262 // Force a commit of any pending writes before issuing deletes.
1263 // TODO(rohitrao): Remove the need for this Commit() by instead pruning the
1264 // list of pending operations. https://crbug.com/486742.
1265 Commit();
1267 sql::Statement del_smt(db_->GetCachedStatement(
1268 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1269 if (!del_smt.is_valid()) {
1270 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1271 return;
1274 sql::Transaction transaction(db_.get());
1275 if (!transaction.Begin()) {
1276 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1277 return;
1280 for (const auto& cookie : cookies) {
1281 const GURL url(cookie_util::CookieOriginToURL(cookie.first, cookie.second));
1282 if (!url.is_valid())
1283 continue;
1285 del_smt.Reset(true);
1286 del_smt.BindString(0, cookie.first);
1287 del_smt.BindInt(1, cookie.second);
1288 if (!del_smt.Run())
1289 NOTREACHED() << "Could not delete a cookie from the DB.";
1292 if (!transaction.Commit())
1293 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1296 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1297 const tracked_objects::Location& origin,
1298 const base::Closure& task) {
1299 if (!background_task_runner_->PostTask(origin, task)) {
1300 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1301 << " to background_task_runner_.";
1305 void SQLitePersistentCookieStore::Backend::PostClientTask(
1306 const tracked_objects::Location& origin,
1307 const base::Closure& task) {
1308 if (!client_task_runner_->PostTask(origin, task)) {
1309 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1310 << " to client_task_runner_.";
1314 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1315 const LoadedCallback& loaded_callback,
1316 bool success) {
1317 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1318 loaded_callback, success));
1321 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1322 const base::FilePath& path,
1323 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1324 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1325 bool restore_old_session_cookies,
1326 CookieCryptoDelegate* crypto_delegate)
1327 : backend_(new Backend(path,
1328 client_task_runner,
1329 background_task_runner,
1330 restore_old_session_cookies,
1331 crypto_delegate)) {
1334 void SQLitePersistentCookieStore::DeleteAllInList(
1335 const std::list<CookieOrigin>& cookies) {
1336 if (backend_)
1337 backend_->DeleteAllInList(cookies);
1340 void SQLitePersistentCookieStore::Close(const base::Closure& callback) {
1341 if (backend_) {
1342 backend_->Close(callback);
1344 // We release our reference to the Backend, though it will probably still
1345 // have a reference if the background runner has not run
1346 // Backend::InternalBackgroundClose() yet.
1347 backend_ = nullptr;
1351 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1352 if (backend_)
1353 backend_->Load(loaded_callback);
1354 else
1355 loaded_callback.Run(std::vector<CanonicalCookie*>());
1358 void SQLitePersistentCookieStore::LoadCookiesForKey(
1359 const std::string& key,
1360 const LoadedCallback& loaded_callback) {
1361 if (backend_)
1362 backend_->LoadCookiesForKey(key, loaded_callback);
1363 else
1364 loaded_callback.Run(std::vector<CanonicalCookie*>());
1367 void SQLitePersistentCookieStore::AddCookie(const CanonicalCookie& cc) {
1368 if (backend_)
1369 backend_->AddCookie(cc);
1372 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1373 const CanonicalCookie& cc) {
1374 if (backend_)
1375 backend_->UpdateCookieAccessTime(cc);
1378 void SQLitePersistentCookieStore::DeleteCookie(const CanonicalCookie& cc) {
1379 if (backend_)
1380 backend_->DeleteCookie(cc);
1383 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1384 // This store never discards session-only cookies, so this call has no effect.
1387 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1388 if (backend_)
1389 backend_->Flush(callback);
1392 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1393 Close(base::Closure());
1396 } // namespace net