Change next_proto member type.
[chromium-blink-merge.git] / content / browser / net / sqlite_persistent_cookie_store.cc
blobdc0b0e20299413c54910172c239f35b0b81b9c02
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/command_line.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/memory/ref_counted.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.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_crypto_delegate.h"
32 #include "content/public/browser/cookie_store_factory.h"
33 #include "content/public/common/content_switches.h"
34 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
35 #include "net/cookies/canonical_cookie.h"
36 #include "net/cookies/cookie_constants.h"
37 #include "net/cookies/cookie_util.h"
38 #include "sql/error_delegate_util.h"
39 #include "sql/meta_table.h"
40 #include "sql/statement.h"
41 #include "sql/transaction.h"
42 #include "storage/browser/quota/special_storage_policy.h"
43 #include "third_party/sqlite/sqlite3.h"
44 #include "url/gurl.h"
46 using base::Time;
48 namespace {
50 const char* kAllAtOnceLoad = "AllAtOnceLoad";
51 const char* kDelayedLoad = "DelayedLoad";
52 const char* kLoadStrategyFieldTrialName = "PersistentCookieStoreLoadStrategy";
53 const int kModerateDelayMilliseconds = 200;
54 const int kMinimalDelayMilliseconds = 0;
56 // Whether instances of this class should use the default load strategy, which
57 // is to sequentially load cookies one eTLD at a time with minimal delay
58 // between loads.
59 bool UseDefaultLoadStrategy() {
60 const std::string group_name =
61 base::FieldTrialList::FindFullName(kLoadStrategyFieldTrialName);
62 return group_name != kDelayedLoad && group_name != kAllAtOnceLoad;
65 // Whether instances of this class should use the delayed load strategy, which
66 // is to sequentially load cookies one eTLD at a time with moderate delay
67 // between loads.
68 bool UseDelayedLoadStrategy() {
69 const std::string group_name =
70 base::FieldTrialList::FindFullName(kLoadStrategyFieldTrialName);
71 return group_name == kDelayedLoad;
74 // Whether instances of this class should use the all at once load strategy,
75 // which is to load all cookies at once.
76 bool UseAllAtOnceLoadStrategy() {
77 const std::string group_name =
78 base::FieldTrialList::FindFullName(kLoadStrategyFieldTrialName);
79 return group_name == kAllAtOnceLoad;
82 } // namespace
84 namespace content {
86 // This class is designed to be shared between any client thread and the
87 // background task runner. It batches operations and commits them on a timer.
89 // SQLitePersistentCookieStore::Load is called to load all cookies. It
90 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
91 // task to the background runner. This task calls Backend::ChainLoadCookies(),
92 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
93 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
94 // posted to the client runner, which notifies the caller of
95 // SQLitePersistentCookieStore::Load that the load is complete.
97 // If a priority load request is invoked via SQLitePersistentCookieStore::
98 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
99 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
100 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
101 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
102 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
104 // Subsequent to loading, mutations may be queued by any thread using
105 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
106 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
107 // whichever occurs first.
108 class SQLitePersistentCookieStore::Backend
109 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
110 public:
111 Backend(
112 const base::FilePath& path,
113 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
114 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
115 bool restore_old_session_cookies,
116 storage::SpecialStoragePolicy* special_storage_policy,
117 CookieCryptoDelegate* crypto_delegate)
118 : path_(path),
119 num_pending_(0),
120 force_keep_session_state_(false),
121 initialized_(false),
122 corruption_detected_(false),
123 restore_old_session_cookies_(restore_old_session_cookies),
124 special_storage_policy_(special_storage_policy),
125 num_cookies_read_(0),
126 client_task_runner_(client_task_runner),
127 background_task_runner_(background_task_runner),
128 num_priority_waiting_(0),
129 total_priority_requests_(0),
130 crypto_(crypto_delegate) {}
132 // Creates or loads the SQLite database.
133 void Load(const LoadedCallback& loaded_callback);
135 // Loads cookies for the domain key (eTLD+1).
136 void LoadCookiesForKey(const std::string& domain,
137 const LoadedCallback& loaded_callback);
139 // Steps through all results of |smt|, makes a cookie from each, and adds the
140 // cookie to |cookies|. This method also updates |cookies_per_origin_| and
141 // |num_cookies_read_|.
142 void MakeCookiesFromSQLStatement(std::vector<net::CanonicalCookie*>* cookies,
143 sql::Statement* statement);
145 // Batch a cookie addition.
146 void AddCookie(const net::CanonicalCookie& cc);
148 // Batch a cookie access time update.
149 void UpdateCookieAccessTime(const net::CanonicalCookie& cc);
151 // Batch a cookie deletion.
152 void DeleteCookie(const net::CanonicalCookie& cc);
154 // Commit pending operations as soon as possible.
155 void Flush(const base::Closure& callback);
157 // Commit any pending operations and close the database. This must be called
158 // before the object is destructed.
159 void Close();
161 void SetForceKeepSessionState();
163 private:
164 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
166 // You should call Close() before destructing this object.
167 ~Backend() {
168 DCHECK(!db_.get()) << "Close should have already been called.";
169 DCHECK(num_pending_ == 0 && pending_.empty());
172 // Database upgrade statements.
173 bool EnsureDatabaseVersion();
175 class PendingOperation {
176 public:
177 typedef enum {
178 COOKIE_ADD,
179 COOKIE_UPDATEACCESS,
180 COOKIE_DELETE,
181 } OperationType;
183 PendingOperation(OperationType op, const net::CanonicalCookie& cc)
184 : op_(op), cc_(cc) { }
186 OperationType op() const { return op_; }
187 const net::CanonicalCookie& cc() const { return cc_; }
189 private:
190 OperationType op_;
191 net::CanonicalCookie cc_;
194 private:
195 // Creates or loads the SQLite database on background runner.
196 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
197 const base::Time& posted_at);
199 // Loads cookies for the domain key (eTLD+1) on background runner.
200 void LoadKeyAndNotifyInBackground(const std::string& domains,
201 const LoadedCallback& loaded_callback,
202 const base::Time& posted_at);
204 // Notifies the CookieMonster when loading completes for a specific domain key
205 // or for all domain keys. Triggers the callback and passes it all cookies
206 // that have been loaded from DB since last IO notification.
207 void Notify(const LoadedCallback& loaded_callback, bool load_success);
209 // Sends notification when the entire store is loaded, and reports metrics
210 // for the total time to load and aggregated results from any priority loads
211 // that occurred.
212 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
213 bool load_success);
215 // Sends notification when a single priority load completes. Updates priority
216 // load metric data. The data is sent only after the final load completes.
217 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
218 bool load_success);
220 // Sends all metrics, including posting a ReportMetricsInBackground task.
221 // Called after all priority and regular loading is complete.
222 void ReportMetrics();
224 // Sends background-runner owned metrics (i.e., the combined duration of all
225 // BG-runner tasks).
226 void ReportMetricsInBackground();
228 // Initialize the data base.
229 bool InitializeDatabase();
231 // Loads cookies for the next domain key from the DB, then either reschedules
232 // itself or schedules the provided callback to run on the client runner (if
233 // all domains are loaded).
234 void ChainLoadCookies(const LoadedCallback& loaded_callback);
236 // Load all cookies for a set of domains/hosts
237 bool LoadCookiesForDomains(const std::set<std::string>& key);
239 // Batch a cookie operation (add or delete)
240 void BatchOperation(PendingOperation::OperationType op,
241 const net::CanonicalCookie& cc);
242 // Commit our pending operations to the database.
243 void Commit();
244 // Close() executed on the background runner.
245 void InternalBackgroundClose();
247 void DeleteSessionCookiesOnStartup();
249 void DeleteSessionCookiesOnShutdown();
251 void DatabaseErrorCallback(int error, sql::Statement* stmt);
252 void KillDatabase();
254 void PostBackgroundTask(const tracked_objects::Location& origin,
255 const base::Closure& task);
256 void PostClientTask(const tracked_objects::Location& origin,
257 const base::Closure& task);
259 // Loads all the cookies from the database at once.
260 bool LoadAllCookies();
262 // Shared code between the different load strategies to be used after all
263 // cookies have been loaded.
264 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
265 bool success);
267 base::FilePath path_;
268 scoped_ptr<sql::Connection> db_;
269 sql::MetaTable meta_table_;
271 typedef std::list<PendingOperation*> PendingOperationsList;
272 PendingOperationsList pending_;
273 PendingOperationsList::size_type num_pending_;
274 // True if the persistent store should skip delete on exit rules.
275 bool force_keep_session_state_;
276 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
277 base::Lock lock_;
279 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
280 // the number of messages sent to the client runner. Sent back in response to
281 // individual load requests for domain keys or when all loading completes.
282 std::vector<net::CanonicalCookie*> cookies_;
284 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
285 std::map<std::string, std::set<std::string> > keys_to_load_;
287 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
288 // database.
289 typedef std::pair<std::string, bool> CookieOrigin;
290 typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
291 CookiesPerOriginMap cookies_per_origin_;
293 // Indicates if DB has been initialized.
294 bool initialized_;
296 // Indicates if the kill-database callback has been scheduled.
297 bool corruption_detected_;
299 // If false, we should filter out session cookies when reading the DB.
300 bool restore_old_session_cookies_;
302 // Policy defining what data is deleted on shutdown.
303 scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_;
305 // The cumulative time spent loading the cookies on the background runner.
306 // Incremented and reported from the background runner.
307 base::TimeDelta cookie_load_duration_;
309 // The total number of cookies read. Incremented and reported on the
310 // background runner.
311 int num_cookies_read_;
313 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
314 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
316 // Guards the following metrics-related properties (only accessed when
317 // starting/completing priority loads or completing the total load).
318 base::Lock metrics_lock_;
319 int num_priority_waiting_;
320 // The total number of priority requests.
321 int total_priority_requests_;
322 // The time when |num_priority_waiting_| incremented to 1.
323 base::Time current_priority_wait_start_;
324 // The cumulative duration of time when |num_priority_waiting_| was greater
325 // than 1.
326 base::TimeDelta priority_wait_duration_;
327 // Class with functions that do cryptographic operations (for protecting
328 // cookies stored persistently).
330 // Not owned.
331 CookieCryptoDelegate* crypto_;
333 DISALLOW_COPY_AND_ASSIGN(Backend);
336 namespace {
338 // Version number of the database.
340 // Version 7 adds encrypted values. Old values will continue to be used but
341 // all new values written will be encrypted on selected operating systems. New
342 // records read by old clients will simply get an empty cookie value while old
343 // records read by new clients will continue to operate with the unencrypted
344 // version. New and old clients alike will always write/update records with
345 // what they support.
347 // Version 6 adds cookie priorities. This allows developers to influence the
348 // order in which cookies are evicted in order to meet domain cookie limits.
350 // Version 5 adds the columns has_expires and is_persistent, so that the
351 // database can store session cookies as well as persistent cookies. Databases
352 // of version 5 are incompatible with older versions of code. If a database of
353 // version 5 is read by older code, session cookies will be treated as normal
354 // cookies. Currently, these fields are written, but not read anymore.
356 // In version 4, we migrated the time epoch. If you open the DB with an older
357 // version on Mac or Linux, the times will look wonky, but the file will likely
358 // be usable. On Windows version 3 and 4 are the same.
360 // Version 3 updated the database to include the last access time, so we can
361 // expire them in decreasing order of use when we've reached the maximum
362 // number of cookies.
363 const int kCurrentVersionNumber = 7;
364 const int kCompatibleVersionNumber = 5;
366 // Possible values for the 'priority' column.
367 enum DBCookiePriority {
368 kCookiePriorityLow = 0,
369 kCookiePriorityMedium = 1,
370 kCookiePriorityHigh = 2,
373 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) {
374 switch (value) {
375 case net::COOKIE_PRIORITY_LOW:
376 return kCookiePriorityLow;
377 case net::COOKIE_PRIORITY_MEDIUM:
378 return kCookiePriorityMedium;
379 case net::COOKIE_PRIORITY_HIGH:
380 return kCookiePriorityHigh;
383 NOTREACHED();
384 return kCookiePriorityMedium;
387 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
388 switch (value) {
389 case kCookiePriorityLow:
390 return net::COOKIE_PRIORITY_LOW;
391 case kCookiePriorityMedium:
392 return net::COOKIE_PRIORITY_MEDIUM;
393 case kCookiePriorityHigh:
394 return net::COOKIE_PRIORITY_HIGH;
397 NOTREACHED();
398 return net::COOKIE_PRIORITY_DEFAULT;
401 // Increments a specified TimeDelta by the duration between this object's
402 // constructor and destructor. Not thread safe. Multiple instances may be
403 // created with the same delta instance as long as their lifetimes are nested.
404 // The shortest lived instances have no impact.
405 class IncrementTimeDelta {
406 public:
407 explicit IncrementTimeDelta(base::TimeDelta* delta) :
408 delta_(delta),
409 original_value_(*delta),
410 start_(base::Time::Now()) {}
412 ~IncrementTimeDelta() {
413 *delta_ = original_value_ + base::Time::Now() - start_;
416 private:
417 base::TimeDelta* delta_;
418 base::TimeDelta original_value_;
419 base::Time start_;
421 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
424 // Initializes the cookies table, returning true on success.
425 bool InitTable(sql::Connection* db) {
426 if (!db->DoesTableExist("cookies")) {
427 std::string stmt(base::StringPrintf(
428 "CREATE TABLE cookies ("
429 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
430 "host_key TEXT NOT NULL,"
431 "name TEXT NOT NULL,"
432 "value TEXT NOT NULL,"
433 "path TEXT NOT NULL,"
434 "expires_utc INTEGER NOT NULL,"
435 "secure INTEGER NOT NULL,"
436 "httponly INTEGER NOT NULL,"
437 "last_access_utc INTEGER NOT NULL, "
438 "has_expires INTEGER NOT NULL DEFAULT 1, "
439 "persistent INTEGER NOT NULL DEFAULT 1,"
440 "priority INTEGER NOT NULL DEFAULT %d,"
441 "encrypted_value BLOB DEFAULT '')",
442 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
443 if (!db->Execute(stmt.c_str()))
444 return false;
447 // Older code created an index on creation_utc, which is already
448 // primary key for the table.
449 if (!db->Execute("DROP INDEX IF EXISTS cookie_times"))
450 return false;
452 if (!db->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
453 return false;
455 return true;
458 } // namespace
460 void SQLitePersistentCookieStore::Backend::Load(
461 const LoadedCallback& loaded_callback) {
462 // This function should be called only once per instance.
463 DCHECK(!db_.get());
464 PostBackgroundTask(FROM_HERE, base::Bind(
465 &Backend::LoadAndNotifyInBackground, this,
466 loaded_callback, base::Time::Now()));
469 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
470 const std::string& key,
471 const LoadedCallback& loaded_callback) {
473 base::AutoLock locked(metrics_lock_);
474 if (num_priority_waiting_ == 0)
475 current_priority_wait_start_ = base::Time::Now();
476 num_priority_waiting_++;
477 total_priority_requests_++;
480 PostBackgroundTask(FROM_HERE, base::Bind(
481 &Backend::LoadKeyAndNotifyInBackground,
482 this, key, loaded_callback, base::Time::Now()));
485 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
486 const LoadedCallback& loaded_callback, const base::Time& posted_at) {
487 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
488 IncrementTimeDelta increment(&cookie_load_duration_);
490 UMA_HISTOGRAM_CUSTOM_TIMES(
491 "Cookie.TimeLoadDBQueueWait",
492 base::Time::Now() - posted_at,
493 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
494 50);
496 if (!InitializeDatabase()) {
497 PostClientTask(FROM_HERE, base::Bind(
498 &Backend::CompleteLoadInForeground, this, loaded_callback, false));
499 } else {
500 if (UseAllAtOnceLoadStrategy())
501 FinishedLoadingCookies(loaded_callback, true);
502 else
503 ChainLoadCookies(loaded_callback);
507 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
508 const std::string& key,
509 const LoadedCallback& loaded_callback,
510 const base::Time& posted_at) {
511 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
512 IncrementTimeDelta increment(&cookie_load_duration_);
514 UMA_HISTOGRAM_CUSTOM_TIMES(
515 "Cookie.TimeKeyLoadDBQueueWait",
516 base::Time::Now() - posted_at,
517 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
518 50);
520 bool success = false;
521 if (InitializeDatabase()) {
522 std::map<std::string, std::set<std::string> >::iterator
523 it = keys_to_load_.find(key);
524 if (it != keys_to_load_.end()) {
525 success = LoadCookiesForDomains(it->second);
526 keys_to_load_.erase(it);
527 } else {
528 success = true;
532 PostClientTask(FROM_HERE, base::Bind(
533 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
534 this, loaded_callback, success));
537 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
538 const LoadedCallback& loaded_callback,
539 bool load_success) {
540 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
542 Notify(loaded_callback, load_success);
545 base::AutoLock locked(metrics_lock_);
546 num_priority_waiting_--;
547 if (num_priority_waiting_ == 0) {
548 priority_wait_duration_ +=
549 base::Time::Now() - current_priority_wait_start_;
555 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
556 UMA_HISTOGRAM_CUSTOM_TIMES(
557 "Cookie.TimeLoad",
558 cookie_load_duration_,
559 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
560 50);
563 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
564 PostBackgroundTask(FROM_HERE, base::Bind(
565 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground, this));
568 base::AutoLock locked(metrics_lock_);
569 UMA_HISTOGRAM_CUSTOM_TIMES(
570 "Cookie.PriorityBlockingTime",
571 priority_wait_duration_,
572 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
573 50);
575 UMA_HISTOGRAM_COUNTS_100(
576 "Cookie.PriorityLoadCount",
577 total_priority_requests_);
579 UMA_HISTOGRAM_COUNTS_10000(
580 "Cookie.NumberOfLoadedCookies",
581 num_cookies_read_);
585 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
586 const LoadedCallback& loaded_callback, bool load_success) {
587 Notify(loaded_callback, load_success);
589 if (load_success)
590 ReportMetrics();
593 void SQLitePersistentCookieStore::Backend::Notify(
594 const LoadedCallback& loaded_callback,
595 bool load_success) {
596 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
598 std::vector<net::CanonicalCookie*> cookies;
600 base::AutoLock locked(lock_);
601 cookies.swap(cookies_);
604 loaded_callback.Run(cookies);
607 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
608 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
610 if (initialized_ || corruption_detected_) {
611 // Return false if we were previously initialized but the DB has since been
612 // closed, or if corruption caused a database reset during initialization.
613 return db_ != NULL;
616 base::Time start = base::Time::Now();
618 const base::FilePath dir = path_.DirName();
619 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
620 return false;
623 int64 db_size = 0;
624 if (base::GetFileSize(path_, &db_size))
625 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024 );
627 db_.reset(new sql::Connection);
628 db_->set_histogram_tag("Cookie");
630 // Unretained to avoid a ref loop with |db_|.
631 db_->set_error_callback(
632 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
633 base::Unretained(this)));
635 if (!db_->Open(path_)) {
636 NOTREACHED() << "Unable to open cookie DB.";
637 if (corruption_detected_)
638 db_->Raze();
639 meta_table_.Reset();
640 db_.reset();
641 return false;
644 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
645 NOTREACHED() << "Unable to open cookie DB.";
646 if (corruption_detected_)
647 db_->Raze();
648 meta_table_.Reset();
649 db_.reset();
650 return false;
653 // When all cookies are going to be loaded at once, there is no longer any
654 // need to get all the domains and eTLDs.
655 if (UseAllAtOnceLoadStrategy()) {
656 bool success = LoadAllCookies();
657 initialized_ = success;
658 return success;
661 UMA_HISTOGRAM_CUSTOM_TIMES(
662 "Cookie.TimeInitializeDB",
663 base::Time::Now() - start,
664 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
665 50);
667 start = base::Time::Now();
669 // Retrieve all the domains
670 sql::Statement smt(db_->GetUniqueStatement(
671 "SELECT DISTINCT host_key FROM cookies"));
673 if (!smt.is_valid()) {
674 if (corruption_detected_)
675 db_->Raze();
676 meta_table_.Reset();
677 db_.reset();
678 return false;
681 std::vector<std::string> host_keys;
682 while (smt.Step())
683 host_keys.push_back(smt.ColumnString(0));
685 UMA_HISTOGRAM_CUSTOM_TIMES(
686 "Cookie.TimeLoadDomains",
687 base::Time::Now() - start,
688 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
689 50);
691 base::Time start_parse = base::Time::Now();
693 // Build a map of domain keys (always eTLD+1) to domains.
694 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
695 const std::string& domain = host_keys[idx];
696 std::string key =
697 net::registry_controlled_domains::GetDomainAndRegistry(
698 domain,
699 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
701 keys_to_load_[key].insert(domain);
704 UMA_HISTOGRAM_CUSTOM_TIMES(
705 "Cookie.TimeParseDomains",
706 base::Time::Now() - start_parse,
707 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
708 50);
710 UMA_HISTOGRAM_CUSTOM_TIMES(
711 "Cookie.TimeInitializeDomainMap",
712 base::Time::Now() - start,
713 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
714 50);
716 initialized_ = true;
717 return true;
720 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
721 const LoadedCallback& loaded_callback) {
722 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
723 IncrementTimeDelta increment(&cookie_load_duration_);
725 bool load_success = true;
727 if (!db_) {
728 // Close() has been called on this store.
729 load_success = false;
730 } else if (keys_to_load_.size() > 0) {
731 // Load cookies for the first domain key.
732 std::map<std::string, std::set<std::string> >::iterator
733 it = keys_to_load_.begin();
734 load_success = LoadCookiesForDomains(it->second);
735 keys_to_load_.erase(it);
738 // If load is successful and there are more domain keys to be loaded,
739 // then post a background task to continue chain-load;
740 // Otherwise notify on client runner.
741 if (load_success && keys_to_load_.size() > 0) {
742 bool use_delayed_load = UseDelayedLoadStrategy();
743 bool use_default_load = UseDefaultLoadStrategy();
744 DCHECK(use_delayed_load || use_default_load);
745 int delay_milliseconds = use_delayed_load ? kModerateDelayMilliseconds
746 : kMinimalDelayMilliseconds;
747 bool success = background_task_runner_->PostDelayedTask(
748 FROM_HERE,
749 base::Bind(&Backend::ChainLoadCookies, this, loaded_callback),
750 base::TimeDelta::FromMilliseconds(delay_milliseconds));
751 if (!success) {
752 LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
753 << " to background_task_runner_.";
755 } else {
756 FinishedLoadingCookies(loaded_callback, load_success);
760 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
761 const std::set<std::string>& domains) {
762 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
764 sql::Statement smt;
765 if (restore_old_session_cookies_) {
766 smt.Assign(db_->GetCachedStatement(
767 SQL_FROM_HERE,
768 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
769 "expires_utc, secure, httponly, last_access_utc, has_expires, "
770 "persistent, priority FROM cookies WHERE host_key = ?"));
771 } else {
772 smt.Assign(db_->GetCachedStatement(
773 SQL_FROM_HERE,
774 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
775 "expires_utc, secure, httponly, last_access_utc, has_expires, "
776 "persistent, priority FROM cookies WHERE host_key = ? "
777 "AND persistent = 1"));
779 if (!smt.is_valid()) {
780 smt.Clear(); // Disconnect smt_ref from db_.
781 meta_table_.Reset();
782 db_.reset();
783 return false;
786 std::vector<net::CanonicalCookie*> cookies;
787 std::set<std::string>::const_iterator it = domains.begin();
788 for (; it != domains.end(); ++it) {
789 smt.BindString(0, *it);
790 MakeCookiesFromSQLStatement(&cookies, &smt);
791 smt.Reset(true);
794 base::AutoLock locked(lock_);
795 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
797 return true;
800 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
801 std::vector<net::CanonicalCookie*>* cookies,
802 sql::Statement* statement) {
803 sql::Statement& smt = *statement;
804 while (smt.Step()) {
805 std::string value;
806 std::string encrypted_value = smt.ColumnString(4);
807 if (!encrypted_value.empty() && crypto_) {
808 crypto_->DecryptString(encrypted_value, &value);
809 } else {
810 DCHECK(encrypted_value.empty());
811 value = smt.ColumnString(3);
813 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie(
814 // The "source" URL is not used with persisted cookies.
815 GURL(), // Source
816 smt.ColumnString(2), // name
817 value, // value
818 smt.ColumnString(1), // domain
819 smt.ColumnString(5), // path
820 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
821 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
822 Time::FromInternalValue(smt.ColumnInt64(9)), // last_access_utc
823 smt.ColumnInt(7) != 0, // secure
824 smt.ColumnInt(8) != 0, // httponly
825 DBCookiePriorityToCookiePriority(
826 static_cast<DBCookiePriority>(smt.ColumnInt(12))))); // priority
827 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
828 << L"CreationDate too recent";
829 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
830 cookies->push_back(cc.release());
831 ++num_cookies_read_;
835 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
836 // Version check.
837 if (!meta_table_.Init(
838 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
839 return false;
842 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
843 LOG(WARNING) << "Cookie database is too new.";
844 return false;
847 int cur_version = meta_table_.GetVersionNumber();
848 if (cur_version == 2) {
849 sql::Transaction transaction(db_.get());
850 if (!transaction.Begin())
851 return false;
852 if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
853 "INTEGER DEFAULT 0") ||
854 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
855 LOG(WARNING) << "Unable to update cookie database to version 3.";
856 return false;
858 ++cur_version;
859 meta_table_.SetVersionNumber(cur_version);
860 meta_table_.SetCompatibleVersionNumber(
861 std::min(cur_version, kCompatibleVersionNumber));
862 transaction.Commit();
865 if (cur_version == 3) {
866 // The time epoch changed for Mac & Linux in this version to match Windows.
867 // This patch came after the main epoch change happened, so some
868 // developers have "good" times for cookies added by the more recent
869 // versions. So we have to be careful to only update times that are under
870 // the old system (which will appear to be from before 1970 in the new
871 // system). The magic number used below is 1970 in our time units.
872 sql::Transaction transaction(db_.get());
873 transaction.Begin();
874 #if !defined(OS_WIN)
875 ignore_result(db_->Execute(
876 "UPDATE cookies "
877 "SET creation_utc = creation_utc + 11644473600000000 "
878 "WHERE rowid IN "
879 "(SELECT rowid FROM cookies WHERE "
880 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
881 ignore_result(db_->Execute(
882 "UPDATE cookies "
883 "SET expires_utc = expires_utc + 11644473600000000 "
884 "WHERE rowid IN "
885 "(SELECT rowid FROM cookies WHERE "
886 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
887 ignore_result(db_->Execute(
888 "UPDATE cookies "
889 "SET last_access_utc = last_access_utc + 11644473600000000 "
890 "WHERE rowid IN "
891 "(SELECT rowid FROM cookies WHERE "
892 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
893 #endif
894 ++cur_version;
895 meta_table_.SetVersionNumber(cur_version);
896 transaction.Commit();
899 if (cur_version == 4) {
900 const base::TimeTicks start_time = base::TimeTicks::Now();
901 sql::Transaction transaction(db_.get());
902 if (!transaction.Begin())
903 return false;
904 if (!db_->Execute("ALTER TABLE cookies "
905 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
906 !db_->Execute("ALTER TABLE cookies "
907 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
908 LOG(WARNING) << "Unable to update cookie database to version 5.";
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.TimeDatabaseMigrationToV5",
917 base::TimeTicks::Now() - start_time);
920 if (cur_version == 5) {
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 the priority column with a default value.
926 std::string stmt(base::StringPrintf(
927 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
928 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
929 if (!db_->Execute(stmt.c_str())) {
930 LOG(WARNING) << "Unable to update cookie database to version 6.";
931 return false;
933 ++cur_version;
934 meta_table_.SetVersionNumber(cur_version);
935 meta_table_.SetCompatibleVersionNumber(
936 std::min(cur_version, kCompatibleVersionNumber));
937 transaction.Commit();
938 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
939 base::TimeTicks::Now() - start_time);
942 if (cur_version == 6) {
943 const base::TimeTicks start_time = base::TimeTicks::Now();
944 sql::Transaction transaction(db_.get());
945 if (!transaction.Begin())
946 return false;
947 // Alter the table to add empty "encrypted value" column.
948 if (!db_->Execute("ALTER TABLE cookies "
949 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
950 LOG(WARNING) << "Unable to update cookie database to version 7.";
951 return false;
953 ++cur_version;
954 meta_table_.SetVersionNumber(cur_version);
955 meta_table_.SetCompatibleVersionNumber(
956 std::min(cur_version, kCompatibleVersionNumber));
957 transaction.Commit();
958 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
959 base::TimeTicks::Now() - start_time);
962 // Put future migration cases here.
964 if (cur_version < kCurrentVersionNumber) {
965 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
967 meta_table_.Reset();
968 db_.reset(new sql::Connection);
969 if (!base::DeleteFile(path_, false) ||
970 !db_->Open(path_) ||
971 !meta_table_.Init(
972 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
973 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
974 NOTREACHED() << "Unable to reset the cookie DB.";
975 meta_table_.Reset();
976 db_.reset();
977 return false;
981 return true;
984 void SQLitePersistentCookieStore::Backend::AddCookie(
985 const net::CanonicalCookie& cc) {
986 BatchOperation(PendingOperation::COOKIE_ADD, cc);
989 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
990 const net::CanonicalCookie& cc) {
991 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
994 void SQLitePersistentCookieStore::Backend::DeleteCookie(
995 const net::CanonicalCookie& cc) {
996 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
999 void SQLitePersistentCookieStore::Backend::BatchOperation(
1000 PendingOperation::OperationType op,
1001 const net::CanonicalCookie& cc) {
1002 // Commit every 30 seconds.
1003 static const int kCommitIntervalMs = 30 * 1000;
1004 // Commit right away if we have more than 512 outstanding operations.
1005 static const size_t kCommitAfterBatchSize = 512;
1006 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1008 // We do a full copy of the cookie here, and hopefully just here.
1009 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1011 PendingOperationsList::size_type num_pending;
1013 base::AutoLock locked(lock_);
1014 pending_.push_back(po.release());
1015 num_pending = ++num_pending_;
1018 if (num_pending == 1) {
1019 // We've gotten our first entry for this batch, fire off the timer.
1020 if (!background_task_runner_->PostDelayedTask(
1021 FROM_HERE, base::Bind(&Backend::Commit, this),
1022 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
1023 NOTREACHED() << "background_task_runner_ is not running.";
1025 } else if (num_pending == kCommitAfterBatchSize) {
1026 // We've reached a big enough batch, fire off a commit now.
1027 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1031 void SQLitePersistentCookieStore::Backend::Commit() {
1032 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1034 PendingOperationsList ops;
1036 base::AutoLock locked(lock_);
1037 pending_.swap(ops);
1038 num_pending_ = 0;
1041 // Maybe an old timer fired or we are already Close()'ed.
1042 if (!db_.get() || ops.empty())
1043 return;
1045 sql::Statement add_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1046 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1047 "encrypted_value, path, expires_utc, secure, httponly, last_access_utc, "
1048 "has_expires, persistent, priority) "
1049 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1050 if (!add_smt.is_valid())
1051 return;
1053 sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1054 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1055 if (!update_access_smt.is_valid())
1056 return;
1058 sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1059 "DELETE FROM cookies WHERE creation_utc=?"));
1060 if (!del_smt.is_valid())
1061 return;
1063 sql::Transaction transaction(db_.get());
1064 if (!transaction.Begin())
1065 return;
1067 for (PendingOperationsList::iterator it = ops.begin();
1068 it != ops.end(); ++it) {
1069 // Free the cookies as we commit them to the database.
1070 scoped_ptr<PendingOperation> po(*it);
1071 switch (po->op()) {
1072 case PendingOperation::COOKIE_ADD:
1073 cookies_per_origin_[
1074 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
1075 add_smt.Reset(true);
1076 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1077 add_smt.BindString(1, po->cc().Domain());
1078 add_smt.BindString(2, po->cc().Name());
1079 if (crypto_) {
1080 std::string encrypted_value;
1081 add_smt.BindCString(3, ""); // value
1082 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1083 // BindBlob() immediately makes an internal copy of the data.
1084 add_smt.BindBlob(4, encrypted_value.data(),
1085 static_cast<int>(encrypted_value.length()));
1086 } else {
1087 add_smt.BindString(3, po->cc().Value());
1088 add_smt.BindBlob(4, "", 0); // encrypted_value
1090 add_smt.BindString(5, po->cc().Path());
1091 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1092 add_smt.BindInt(7, po->cc().IsSecure());
1093 add_smt.BindInt(8, po->cc().IsHttpOnly());
1094 add_smt.BindInt64(9, po->cc().LastAccessDate().ToInternalValue());
1095 add_smt.BindInt(10, po->cc().IsPersistent());
1096 add_smt.BindInt(11, po->cc().IsPersistent());
1097 add_smt.BindInt(
1098 12, CookiePriorityToDBCookiePriority(po->cc().Priority()));
1099 if (!add_smt.Run())
1100 NOTREACHED() << "Could not add a cookie to the DB.";
1101 break;
1103 case PendingOperation::COOKIE_UPDATEACCESS:
1104 update_access_smt.Reset(true);
1105 update_access_smt.BindInt64(0,
1106 po->cc().LastAccessDate().ToInternalValue());
1107 update_access_smt.BindInt64(1,
1108 po->cc().CreationDate().ToInternalValue());
1109 if (!update_access_smt.Run())
1110 NOTREACHED() << "Could not update cookie last access time in the DB.";
1111 break;
1113 case PendingOperation::COOKIE_DELETE:
1114 cookies_per_origin_[
1115 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1116 del_smt.Reset(true);
1117 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1118 if (!del_smt.Run())
1119 NOTREACHED() << "Could not delete a cookie from the DB.";
1120 break;
1122 default:
1123 NOTREACHED();
1124 break;
1127 bool succeeded = transaction.Commit();
1128 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1129 succeeded ? 0 : 1, 2);
1132 void SQLitePersistentCookieStore::Backend::Flush(
1133 const base::Closure& callback) {
1134 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1135 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1137 if (!callback.is_null()) {
1138 // We want the completion task to run immediately after Commit() returns.
1139 // Posting it from here means there is less chance of another task getting
1140 // onto the message queue first, than if we posted it from Commit() itself.
1141 PostBackgroundTask(FROM_HERE, callback);
1145 // Fire off a close message to the background runner. We could still have a
1146 // pending commit timer or Load operations holding references on us, but if/when
1147 // this fires we will already have been cleaned up and it will be ignored.
1148 void SQLitePersistentCookieStore::Backend::Close() {
1149 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1150 InternalBackgroundClose();
1151 } else {
1152 // Must close the backend on the background runner.
1153 PostBackgroundTask(FROM_HERE,
1154 base::Bind(&Backend::InternalBackgroundClose, this));
1158 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1159 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1160 // Commit any pending operations
1161 Commit();
1163 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1164 special_storage_policy_->HasSessionOnlyOrigins()) {
1165 DeleteSessionCookiesOnShutdown();
1168 meta_table_.Reset();
1169 db_.reset();
1172 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1173 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1175 if (!db_)
1176 return;
1178 if (!special_storage_policy_.get())
1179 return;
1181 sql::Statement del_smt(db_->GetCachedStatement(
1182 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1183 if (!del_smt.is_valid()) {
1184 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1185 return;
1188 sql::Transaction transaction(db_.get());
1189 if (!transaction.Begin()) {
1190 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1191 return;
1194 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1195 it != cookies_per_origin_.end(); ++it) {
1196 if (it->second <= 0) {
1197 DCHECK_EQ(0, it->second);
1198 continue;
1200 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1201 it->first.second));
1202 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1203 continue;
1205 del_smt.Reset(true);
1206 del_smt.BindString(0, it->first.first);
1207 del_smt.BindInt(1, it->first.second);
1208 if (!del_smt.Run())
1209 NOTREACHED() << "Could not delete a cookie from the DB.";
1212 if (!transaction.Commit())
1213 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1216 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1217 int error,
1218 sql::Statement* stmt) {
1219 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1221 if (!sql::IsErrorCatastrophic(error))
1222 return;
1224 // TODO(shess): Running KillDatabase() multiple times should be
1225 // safe.
1226 if (corruption_detected_)
1227 return;
1229 corruption_detected_ = true;
1231 // Don't just do the close/delete here, as we are being called by |db| and
1232 // that seems dangerous.
1233 // TODO(shess): Consider just calling RazeAndClose() immediately.
1234 // db_ may not be safe to reset at this point, but RazeAndClose()
1235 // would cause the stack to unwind safely with errors.
1236 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1239 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1240 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1242 if (db_) {
1243 // This Backend will now be in-memory only. In a future run we will recreate
1244 // the database. Hopefully things go better then!
1245 bool success = db_->RazeAndClose();
1246 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1247 meta_table_.Reset();
1248 db_.reset();
1252 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1253 base::AutoLock locked(lock_);
1254 force_keep_session_state_ = true;
1257 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1258 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1259 if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0"))
1260 LOG(WARNING) << "Unable to delete session cookies.";
1263 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1264 const tracked_objects::Location& origin, const base::Closure& task) {
1265 if (!background_task_runner_->PostTask(origin, task)) {
1266 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1267 << " to background_task_runner_.";
1271 void SQLitePersistentCookieStore::Backend::PostClientTask(
1272 const tracked_objects::Location& origin, const base::Closure& task) {
1273 if (!client_task_runner_->PostTask(origin, task)) {
1274 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1275 << " to client_task_runner_.";
1279 bool SQLitePersistentCookieStore::Backend::LoadAllCookies() {
1280 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1282 sql::Statement smt;
1283 if (restore_old_session_cookies_) {
1284 smt.Assign(db_->GetCachedStatement(
1285 SQL_FROM_HERE,
1286 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
1287 "expires_utc, secure, httponly, last_access_utc, has_expires, "
1288 "persistent, priority FROM cookies"));
1289 } else {
1290 smt.Assign(db_->GetCachedStatement(
1291 SQL_FROM_HERE,
1292 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
1293 "expires_utc, secure, httponly, last_access_utc, has_expires, "
1294 "persistent, priority FROM cookies WHERE persistent = 1"));
1296 if (!smt.is_valid()) {
1297 smt.Clear(); // Disconnect smt_ref from db_.
1298 meta_table_.Reset();
1299 db_.reset();
1300 return false;
1303 std::vector<net::CanonicalCookie*> cookies;
1304 MakeCookiesFromSQLStatement(&cookies, &smt);
1305 smt.Reset(true);
1307 base::AutoLock locked(lock_);
1308 DCHECK(cookies_.empty());
1309 cookies_.swap(cookies);
1312 return true;
1315 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1316 const LoadedCallback& loaded_callback,
1317 bool success) {
1318 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1319 loaded_callback, success));
1320 if (success && !restore_old_session_cookies_)
1321 DeleteSessionCookiesOnStartup();
1324 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1325 const base::FilePath& path,
1326 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1327 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1328 bool restore_old_session_cookies,
1329 storage::SpecialStoragePolicy* special_storage_policy,
1330 CookieCryptoDelegate* crypto_delegate)
1331 : backend_(new Backend(path,
1332 client_task_runner,
1333 background_task_runner,
1334 restore_old_session_cookies,
1335 special_storage_policy,
1336 crypto_delegate)) {
1339 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1340 backend_->Load(loaded_callback);
1343 void SQLitePersistentCookieStore::LoadCookiesForKey(
1344 const std::string& key,
1345 const LoadedCallback& loaded_callback) {
1346 backend_->LoadCookiesForKey(key, loaded_callback);
1349 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) {
1350 backend_->AddCookie(cc);
1353 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1354 const net::CanonicalCookie& cc) {
1355 backend_->UpdateCookieAccessTime(cc);
1358 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) {
1359 backend_->DeleteCookie(cc);
1362 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1363 backend_->SetForceKeepSessionState();
1366 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1367 backend_->Flush(callback);
1370 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1371 backend_->Close();
1372 // We release our reference to the Backend, though it will probably still have
1373 // a reference if the background runner has not run Close() yet.
1376 CookieStoreConfig::CookieStoreConfig()
1377 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1378 crypto_delegate(NULL) {
1379 // Default to an in-memory cookie store.
1382 CookieStoreConfig::CookieStoreConfig(
1383 const base::FilePath& path,
1384 SessionCookieMode session_cookie_mode,
1385 storage::SpecialStoragePolicy* storage_policy,
1386 net::CookieMonsterDelegate* cookie_delegate)
1387 : path(path),
1388 session_cookie_mode(session_cookie_mode),
1389 storage_policy(storage_policy),
1390 cookie_delegate(cookie_delegate),
1391 crypto_delegate(NULL) {
1392 CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1395 CookieStoreConfig::~CookieStoreConfig() {
1398 net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1399 net::CookieMonster* cookie_monster = NULL;
1401 if (config.path.empty()) {
1402 // Empty path means in-memory store.
1403 cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate.get());
1404 } else {
1405 scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1406 config.client_task_runner;
1407 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1408 config.background_task_runner;
1410 if (!client_task_runner.get()) {
1411 client_task_runner =
1412 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1415 if (!background_task_runner.get()) {
1416 background_task_runner =
1417 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1418 BrowserThread::GetBlockingPool()->GetSequenceToken());
1421 SQLitePersistentCookieStore* persistent_store =
1422 new SQLitePersistentCookieStore(
1423 config.path,
1424 client_task_runner,
1425 background_task_runner,
1426 (config.session_cookie_mode ==
1427 CookieStoreConfig::RESTORED_SESSION_COOKIES),
1428 config.storage_policy.get(),
1429 config.crypto_delegate);
1431 cookie_monster =
1432 new net::CookieMonster(persistent_store, config.cookie_delegate.get());
1433 if ((config.session_cookie_mode ==
1434 CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1435 (config.session_cookie_mode ==
1436 CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1437 cookie_monster->SetPersistSessionCookies(true);
1441 if (CommandLine::ForCurrentProcess()->HasSwitch(
1442 switches::kEnableFileCookies)) {
1443 cookie_monster->SetEnableFileScheme(true);
1446 return cookie_monster;
1449 } // namespace content