Revert 268405 "Make sure that ScratchBuffer::Allocate() always r..."
[chromium-blink-merge.git] / content / browser / net / sqlite_persistent_cookie_store.cc
blob967101f4dbb2ba09b5d6f443f7c0b3034175674f
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/file_util.h"
17 #include "base/files/file_path.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/histogram.h"
23 #include "base/sequenced_task_runner.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/time/time.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/browser/cookie_crypto_delegate.h"
31 #include "content/public/browser/cookie_store_factory.h"
32 #include "content/public/common/content_switches.h"
33 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
34 #include "net/cookies/canonical_cookie.h"
35 #include "net/cookies/cookie_constants.h"
36 #include "net/cookies/cookie_util.h"
37 #include "sql/error_delegate_util.h"
38 #include "sql/meta_table.h"
39 #include "sql/statement.h"
40 #include "sql/transaction.h"
41 #include "third_party/sqlite/sqlite3.h"
42 #include "url/gurl.h"
43 #include "webkit/browser/quota/special_storage_policy.h"
45 using base::Time;
47 namespace content {
49 // This class is designed to be shared between any client thread and the
50 // background task runner. It batches operations and commits them on a timer.
52 // SQLitePersistentCookieStore::Load is called to load all cookies. It
53 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
54 // task to the background runner. This task calls Backend::ChainLoadCookies(),
55 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
56 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
57 // posted to the client runner, which notifies the caller of
58 // SQLitePersistentCookieStore::Load that the load is complete.
60 // If a priority load request is invoked via SQLitePersistentCookieStore::
61 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
62 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
63 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
64 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
65 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
67 // Subsequent to loading, mutations may be queued by any thread using
68 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
69 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
70 // whichever occurs first.
71 class SQLitePersistentCookieStore::Backend
72 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
73 public:
74 Backend(
75 const base::FilePath& path,
76 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
77 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
78 bool restore_old_session_cookies,
79 quota::SpecialStoragePolicy* special_storage_policy,
80 CookieCryptoDelegate* crypto_delegate)
81 : path_(path),
82 num_pending_(0),
83 force_keep_session_state_(false),
84 initialized_(false),
85 corruption_detected_(false),
86 restore_old_session_cookies_(restore_old_session_cookies),
87 special_storage_policy_(special_storage_policy),
88 num_cookies_read_(0),
89 client_task_runner_(client_task_runner),
90 background_task_runner_(background_task_runner),
91 num_priority_waiting_(0),
92 total_priority_requests_(0),
93 crypto_(crypto_delegate) {}
95 // Creates or loads the SQLite database.
96 void Load(const LoadedCallback& loaded_callback);
98 // Loads cookies for the domain key (eTLD+1).
99 void LoadCookiesForKey(const std::string& domain,
100 const LoadedCallback& loaded_callback);
102 // Batch a cookie addition.
103 void AddCookie(const net::CanonicalCookie& cc);
105 // Batch a cookie access time update.
106 void UpdateCookieAccessTime(const net::CanonicalCookie& cc);
108 // Batch a cookie deletion.
109 void DeleteCookie(const net::CanonicalCookie& cc);
111 // Commit pending operations as soon as possible.
112 void Flush(const base::Closure& callback);
114 // Commit any pending operations and close the database. This must be called
115 // before the object is destructed.
116 void Close();
118 void SetForceKeepSessionState();
120 private:
121 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
123 // You should call Close() before destructing this object.
124 ~Backend() {
125 DCHECK(!db_.get()) << "Close should have already been called.";
126 DCHECK(num_pending_ == 0 && pending_.empty());
129 // Database upgrade statements.
130 bool EnsureDatabaseVersion();
132 class PendingOperation {
133 public:
134 typedef enum {
135 COOKIE_ADD,
136 COOKIE_UPDATEACCESS,
137 COOKIE_DELETE,
138 } OperationType;
140 PendingOperation(OperationType op, const net::CanonicalCookie& cc)
141 : op_(op), cc_(cc) { }
143 OperationType op() const { return op_; }
144 const net::CanonicalCookie& cc() const { return cc_; }
146 private:
147 OperationType op_;
148 net::CanonicalCookie cc_;
151 private:
152 // Creates or loads the SQLite database on background runner.
153 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
154 const base::Time& posted_at);
156 // Loads cookies for the domain key (eTLD+1) on background runner.
157 void LoadKeyAndNotifyInBackground(const std::string& domains,
158 const LoadedCallback& loaded_callback,
159 const base::Time& posted_at);
161 // Notifies the CookieMonster when loading completes for a specific domain key
162 // or for all domain keys. Triggers the callback and passes it all cookies
163 // that have been loaded from DB since last IO notification.
164 void Notify(const LoadedCallback& loaded_callback, bool load_success);
166 // Sends notification when the entire store is loaded, and reports metrics
167 // for the total time to load and aggregated results from any priority loads
168 // that occurred.
169 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
170 bool load_success);
172 // Sends notification when a single priority load completes. Updates priority
173 // load metric data. The data is sent only after the final load completes.
174 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
175 bool load_success);
177 // Sends all metrics, including posting a ReportMetricsInBackground task.
178 // Called after all priority and regular loading is complete.
179 void ReportMetrics();
181 // Sends background-runner owned metrics (i.e., the combined duration of all
182 // BG-runner tasks).
183 void ReportMetricsInBackground();
185 // Initialize the data base.
186 bool InitializeDatabase();
188 // Loads cookies for the next domain key from the DB, then either reschedules
189 // itself or schedules the provided callback to run on the client runner (if
190 // all domains are loaded).
191 void ChainLoadCookies(const LoadedCallback& loaded_callback);
193 // Load all cookies for a set of domains/hosts
194 bool LoadCookiesForDomains(const std::set<std::string>& key);
196 // Batch a cookie operation (add or delete)
197 void BatchOperation(PendingOperation::OperationType op,
198 const net::CanonicalCookie& cc);
199 // Commit our pending operations to the database.
200 void Commit();
201 // Close() executed on the background runner.
202 void InternalBackgroundClose();
204 void DeleteSessionCookiesOnStartup();
206 void DeleteSessionCookiesOnShutdown();
208 void DatabaseErrorCallback(int error, sql::Statement* stmt);
209 void KillDatabase();
211 void PostBackgroundTask(const tracked_objects::Location& origin,
212 const base::Closure& task);
213 void PostClientTask(const tracked_objects::Location& origin,
214 const base::Closure& task);
216 base::FilePath path_;
217 scoped_ptr<sql::Connection> db_;
218 sql::MetaTable meta_table_;
220 typedef std::list<PendingOperation*> PendingOperationsList;
221 PendingOperationsList pending_;
222 PendingOperationsList::size_type num_pending_;
223 // True if the persistent store should skip delete on exit rules.
224 bool force_keep_session_state_;
225 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
226 base::Lock lock_;
228 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
229 // the number of messages sent to the client runner. Sent back in response to
230 // individual load requests for domain keys or when all loading completes.
231 std::vector<net::CanonicalCookie*> cookies_;
233 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
234 std::map<std::string, std::set<std::string> > keys_to_load_;
236 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
237 // database.
238 typedef std::pair<std::string, bool> CookieOrigin;
239 typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
240 CookiesPerOriginMap cookies_per_origin_;
242 // Indicates if DB has been initialized.
243 bool initialized_;
245 // Indicates if the kill-database callback has been scheduled.
246 bool corruption_detected_;
248 // If false, we should filter out session cookies when reading the DB.
249 bool restore_old_session_cookies_;
251 // Policy defining what data is deleted on shutdown.
252 scoped_refptr<quota::SpecialStoragePolicy> special_storage_policy_;
254 // The cumulative time spent loading the cookies on the background runner.
255 // Incremented and reported from the background runner.
256 base::TimeDelta cookie_load_duration_;
258 // The total number of cookies read. Incremented and reported on the
259 // background runner.
260 int num_cookies_read_;
262 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
263 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
265 // Guards the following metrics-related properties (only accessed when
266 // starting/completing priority loads or completing the total load).
267 base::Lock metrics_lock_;
268 int num_priority_waiting_;
269 // The total number of priority requests.
270 int total_priority_requests_;
271 // The time when |num_priority_waiting_| incremented to 1.
272 base::Time current_priority_wait_start_;
273 // The cumulative duration of time when |num_priority_waiting_| was greater
274 // than 1.
275 base::TimeDelta priority_wait_duration_;
276 // Class with functions that do cryptographic operations (for protecting
277 // cookies stored persistently).
279 // Not owned.
280 CookieCryptoDelegate* crypto_;
282 DISALLOW_COPY_AND_ASSIGN(Backend);
285 namespace {
287 // Version number of the database.
289 // Version 7 adds encrypted values. Old values will continue to be used but
290 // all new values written will be encrypted on selected operating systems. New
291 // records read by old clients will simply get an empty cookie value while old
292 // records read by new clients will continue to operate with the unencrypted
293 // version. New and old clients alike will always write/update records with
294 // what they support.
296 // Version 6 adds cookie priorities. This allows developers to influence the
297 // order in which cookies are evicted in order to meet domain cookie limits.
299 // Version 5 adds the columns has_expires and is_persistent, so that the
300 // database can store session cookies as well as persistent cookies. Databases
301 // of version 5 are incompatible with older versions of code. If a database of
302 // version 5 is read by older code, session cookies will be treated as normal
303 // cookies. Currently, these fields are written, but not read anymore.
305 // In version 4, we migrated the time epoch. If you open the DB with an older
306 // version on Mac or Linux, the times will look wonky, but the file will likely
307 // be usable. On Windows version 3 and 4 are the same.
309 // Version 3 updated the database to include the last access time, so we can
310 // expire them in decreasing order of use when we've reached the maximum
311 // number of cookies.
312 const int kCurrentVersionNumber = 7;
313 const int kCompatibleVersionNumber = 5;
315 // Possible values for the 'priority' column.
316 enum DBCookiePriority {
317 kCookiePriorityLow = 0,
318 kCookiePriorityMedium = 1,
319 kCookiePriorityHigh = 2,
322 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) {
323 switch (value) {
324 case net::COOKIE_PRIORITY_LOW:
325 return kCookiePriorityLow;
326 case net::COOKIE_PRIORITY_MEDIUM:
327 return kCookiePriorityMedium;
328 case net::COOKIE_PRIORITY_HIGH:
329 return kCookiePriorityHigh;
332 NOTREACHED();
333 return kCookiePriorityMedium;
336 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
337 switch (value) {
338 case kCookiePriorityLow:
339 return net::COOKIE_PRIORITY_LOW;
340 case kCookiePriorityMedium:
341 return net::COOKIE_PRIORITY_MEDIUM;
342 case kCookiePriorityHigh:
343 return net::COOKIE_PRIORITY_HIGH;
346 NOTREACHED();
347 return net::COOKIE_PRIORITY_DEFAULT;
350 // Increments a specified TimeDelta by the duration between this object's
351 // constructor and destructor. Not thread safe. Multiple instances may be
352 // created with the same delta instance as long as their lifetimes are nested.
353 // The shortest lived instances have no impact.
354 class IncrementTimeDelta {
355 public:
356 explicit IncrementTimeDelta(base::TimeDelta* delta) :
357 delta_(delta),
358 original_value_(*delta),
359 start_(base::Time::Now()) {}
361 ~IncrementTimeDelta() {
362 *delta_ = original_value_ + base::Time::Now() - start_;
365 private:
366 base::TimeDelta* delta_;
367 base::TimeDelta original_value_;
368 base::Time start_;
370 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
373 // Initializes the cookies table, returning true on success.
374 bool InitTable(sql::Connection* db) {
375 if (!db->DoesTableExist("cookies")) {
376 std::string stmt(base::StringPrintf(
377 "CREATE TABLE cookies ("
378 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
379 "host_key TEXT NOT NULL,"
380 "name TEXT NOT NULL,"
381 "value TEXT NOT NULL,"
382 "path TEXT NOT NULL,"
383 "expires_utc INTEGER NOT NULL,"
384 "secure INTEGER NOT NULL,"
385 "httponly INTEGER NOT NULL,"
386 "last_access_utc INTEGER NOT NULL, "
387 "has_expires INTEGER NOT NULL DEFAULT 1, "
388 "persistent INTEGER NOT NULL DEFAULT 1,"
389 "priority INTEGER NOT NULL DEFAULT %d,"
390 "encrypted_value BLOB DEFAULT '')",
391 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
392 if (!db->Execute(stmt.c_str()))
393 return false;
396 // Older code created an index on creation_utc, which is already
397 // primary key for the table.
398 if (!db->Execute("DROP INDEX IF EXISTS cookie_times"))
399 return false;
401 if (!db->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
402 return false;
404 return true;
407 } // namespace
409 void SQLitePersistentCookieStore::Backend::Load(
410 const LoadedCallback& loaded_callback) {
411 // This function should be called only once per instance.
412 DCHECK(!db_.get());
413 PostBackgroundTask(FROM_HERE, base::Bind(
414 &Backend::LoadAndNotifyInBackground, this,
415 loaded_callback, base::Time::Now()));
418 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
419 const std::string& key,
420 const LoadedCallback& loaded_callback) {
422 base::AutoLock locked(metrics_lock_);
423 if (num_priority_waiting_ == 0)
424 current_priority_wait_start_ = base::Time::Now();
425 num_priority_waiting_++;
426 total_priority_requests_++;
429 PostBackgroundTask(FROM_HERE, base::Bind(
430 &Backend::LoadKeyAndNotifyInBackground,
431 this, key, loaded_callback, base::Time::Now()));
434 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
435 const LoadedCallback& loaded_callback, const base::Time& posted_at) {
436 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
437 IncrementTimeDelta increment(&cookie_load_duration_);
439 UMA_HISTOGRAM_CUSTOM_TIMES(
440 "Cookie.TimeLoadDBQueueWait",
441 base::Time::Now() - posted_at,
442 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
443 50);
445 if (!InitializeDatabase()) {
446 PostClientTask(FROM_HERE, base::Bind(
447 &Backend::CompleteLoadInForeground, this, loaded_callback, false));
448 } else {
449 ChainLoadCookies(loaded_callback);
453 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
454 const std::string& key,
455 const LoadedCallback& loaded_callback,
456 const base::Time& posted_at) {
457 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
458 IncrementTimeDelta increment(&cookie_load_duration_);
460 UMA_HISTOGRAM_CUSTOM_TIMES(
461 "Cookie.TimeKeyLoadDBQueueWait",
462 base::Time::Now() - posted_at,
463 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
464 50);
466 bool success = false;
467 if (InitializeDatabase()) {
468 std::map<std::string, std::set<std::string> >::iterator
469 it = keys_to_load_.find(key);
470 if (it != keys_to_load_.end()) {
471 success = LoadCookiesForDomains(it->second);
472 keys_to_load_.erase(it);
473 } else {
474 success = true;
478 PostClientTask(FROM_HERE, base::Bind(
479 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
480 this, loaded_callback, success));
483 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
484 const LoadedCallback& loaded_callback,
485 bool load_success) {
486 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
488 Notify(loaded_callback, load_success);
491 base::AutoLock locked(metrics_lock_);
492 num_priority_waiting_--;
493 if (num_priority_waiting_ == 0) {
494 priority_wait_duration_ +=
495 base::Time::Now() - current_priority_wait_start_;
501 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
502 UMA_HISTOGRAM_CUSTOM_TIMES(
503 "Cookie.TimeLoad",
504 cookie_load_duration_,
505 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
506 50);
509 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
510 PostBackgroundTask(FROM_HERE, base::Bind(
511 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground, this));
514 base::AutoLock locked(metrics_lock_);
515 UMA_HISTOGRAM_CUSTOM_TIMES(
516 "Cookie.PriorityBlockingTime",
517 priority_wait_duration_,
518 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
519 50);
521 UMA_HISTOGRAM_COUNTS_100(
522 "Cookie.PriorityLoadCount",
523 total_priority_requests_);
525 UMA_HISTOGRAM_COUNTS_10000(
526 "Cookie.NumberOfLoadedCookies",
527 num_cookies_read_);
531 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
532 const LoadedCallback& loaded_callback, bool load_success) {
533 Notify(loaded_callback, load_success);
535 if (load_success)
536 ReportMetrics();
539 void SQLitePersistentCookieStore::Backend::Notify(
540 const LoadedCallback& loaded_callback,
541 bool load_success) {
542 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
544 std::vector<net::CanonicalCookie*> cookies;
546 base::AutoLock locked(lock_);
547 cookies.swap(cookies_);
550 loaded_callback.Run(cookies);
553 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
554 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
556 if (initialized_ || corruption_detected_) {
557 // Return false if we were previously initialized but the DB has since been
558 // closed, or if corruption caused a database reset during initialization.
559 return db_ != NULL;
562 base::Time start = base::Time::Now();
564 const base::FilePath dir = path_.DirName();
565 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
566 return false;
569 int64 db_size = 0;
570 if (base::GetFileSize(path_, &db_size))
571 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024 );
573 db_.reset(new sql::Connection);
574 db_->set_histogram_tag("Cookie");
576 // Unretained to avoid a ref loop with |db_|.
577 db_->set_error_callback(
578 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
579 base::Unretained(this)));
581 if (!db_->Open(path_)) {
582 NOTREACHED() << "Unable to open cookie DB.";
583 if (corruption_detected_)
584 db_->Raze();
585 meta_table_.Reset();
586 db_.reset();
587 return false;
590 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
591 NOTREACHED() << "Unable to open cookie DB.";
592 if (corruption_detected_)
593 db_->Raze();
594 meta_table_.Reset();
595 db_.reset();
596 return false;
599 UMA_HISTOGRAM_CUSTOM_TIMES(
600 "Cookie.TimeInitializeDB",
601 base::Time::Now() - start,
602 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
603 50);
605 start = base::Time::Now();
607 // Retrieve all the domains
608 sql::Statement smt(db_->GetUniqueStatement(
609 "SELECT DISTINCT host_key FROM cookies"));
611 if (!smt.is_valid()) {
612 if (corruption_detected_)
613 db_->Raze();
614 meta_table_.Reset();
615 db_.reset();
616 return false;
619 std::vector<std::string> host_keys;
620 while (smt.Step())
621 host_keys.push_back(smt.ColumnString(0));
623 UMA_HISTOGRAM_CUSTOM_TIMES(
624 "Cookie.TimeLoadDomains",
625 base::Time::Now() - start,
626 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
627 50);
629 base::Time start_parse = base::Time::Now();
631 // Build a map of domain keys (always eTLD+1) to domains.
632 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
633 const std::string& domain = host_keys[idx];
634 std::string key =
635 net::registry_controlled_domains::GetDomainAndRegistry(
636 domain,
637 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
639 keys_to_load_[key].insert(domain);
642 UMA_HISTOGRAM_CUSTOM_TIMES(
643 "Cookie.TimeParseDomains",
644 base::Time::Now() - start_parse,
645 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
646 50);
648 UMA_HISTOGRAM_CUSTOM_TIMES(
649 "Cookie.TimeInitializeDomainMap",
650 base::Time::Now() - start,
651 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
652 50);
654 initialized_ = true;
655 return true;
658 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
659 const LoadedCallback& loaded_callback) {
660 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
661 IncrementTimeDelta increment(&cookie_load_duration_);
663 bool load_success = true;
665 if (!db_) {
666 // Close() has been called on this store.
667 load_success = false;
668 } else if (keys_to_load_.size() > 0) {
669 // Load cookies for the first domain key.
670 std::map<std::string, std::set<std::string> >::iterator
671 it = keys_to_load_.begin();
672 load_success = LoadCookiesForDomains(it->second);
673 keys_to_load_.erase(it);
676 // If load is successful and there are more domain keys to be loaded,
677 // then post a background task to continue chain-load;
678 // Otherwise notify on client runner.
679 if (load_success && keys_to_load_.size() > 0) {
680 PostBackgroundTask(FROM_HERE, base::Bind(
681 &Backend::ChainLoadCookies, this, loaded_callback));
682 } else {
683 PostClientTask(FROM_HERE, base::Bind(
684 &Backend::CompleteLoadInForeground, this,
685 loaded_callback, load_success));
686 if (load_success && !restore_old_session_cookies_)
687 DeleteSessionCookiesOnStartup();
691 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
692 const std::set<std::string>& domains) {
693 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
695 sql::Statement smt;
696 if (restore_old_session_cookies_) {
697 smt.Assign(db_->GetCachedStatement(
698 SQL_FROM_HERE,
699 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
700 "expires_utc, secure, httponly, last_access_utc, has_expires, "
701 "persistent, priority FROM cookies WHERE host_key = ?"));
702 } else {
703 smt.Assign(db_->GetCachedStatement(
704 SQL_FROM_HERE,
705 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
706 "expires_utc, secure, httponly, last_access_utc, has_expires, "
707 "persistent, priority FROM cookies WHERE host_key = ? "
708 "AND persistent = 1"));
710 if (!smt.is_valid()) {
711 smt.Clear(); // Disconnect smt_ref from db_.
712 meta_table_.Reset();
713 db_.reset();
714 return false;
717 std::vector<net::CanonicalCookie*> cookies;
718 std::set<std::string>::const_iterator it = domains.begin();
719 for (; it != domains.end(); ++it) {
720 smt.BindString(0, *it);
721 while (smt.Step()) {
722 std::string value;
723 std::string encrypted_value = smt.ColumnString(4);
724 if (!encrypted_value.empty() && crypto_) {
725 crypto_->DecryptString(encrypted_value, &value);
726 } else {
727 DCHECK(encrypted_value.empty());
728 value = smt.ColumnString(3);
730 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie(
731 // The "source" URL is not used with persisted cookies.
732 GURL(), // Source
733 smt.ColumnString(2), // name
734 value, // value
735 smt.ColumnString(1), // domain
736 smt.ColumnString(5), // path
737 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
738 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
739 Time::FromInternalValue(smt.ColumnInt64(9)), // last_access_utc
740 smt.ColumnInt(7) != 0, // secure
741 smt.ColumnInt(8) != 0, // httponly
742 DBCookiePriorityToCookiePriority(
743 static_cast<DBCookiePriority>(smt.ColumnInt(12))))); // priority
744 DLOG_IF(WARNING,
745 cc->CreationDate() > Time::Now()) << L"CreationDate too recent";
746 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
747 cookies.push_back(cc.release());
748 ++num_cookies_read_;
750 smt.Reset(true);
753 base::AutoLock locked(lock_);
754 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
756 return true;
759 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
760 // Version check.
761 if (!meta_table_.Init(
762 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
763 return false;
766 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
767 LOG(WARNING) << "Cookie database is too new.";
768 return false;
771 int cur_version = meta_table_.GetVersionNumber();
772 if (cur_version == 2) {
773 sql::Transaction transaction(db_.get());
774 if (!transaction.Begin())
775 return false;
776 if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
777 "INTEGER DEFAULT 0") ||
778 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
779 LOG(WARNING) << "Unable to update cookie database to version 3.";
780 return false;
782 ++cur_version;
783 meta_table_.SetVersionNumber(cur_version);
784 meta_table_.SetCompatibleVersionNumber(
785 std::min(cur_version, kCompatibleVersionNumber));
786 transaction.Commit();
789 if (cur_version == 3) {
790 // The time epoch changed for Mac & Linux in this version to match Windows.
791 // This patch came after the main epoch change happened, so some
792 // developers have "good" times for cookies added by the more recent
793 // versions. So we have to be careful to only update times that are under
794 // the old system (which will appear to be from before 1970 in the new
795 // system). The magic number used below is 1970 in our time units.
796 sql::Transaction transaction(db_.get());
797 transaction.Begin();
798 #if !defined(OS_WIN)
799 ignore_result(db_->Execute(
800 "UPDATE cookies "
801 "SET creation_utc = creation_utc + 11644473600000000 "
802 "WHERE rowid IN "
803 "(SELECT rowid FROM cookies WHERE "
804 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
805 ignore_result(db_->Execute(
806 "UPDATE cookies "
807 "SET expires_utc = expires_utc + 11644473600000000 "
808 "WHERE rowid IN "
809 "(SELECT rowid FROM cookies WHERE "
810 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
811 ignore_result(db_->Execute(
812 "UPDATE cookies "
813 "SET last_access_utc = last_access_utc + 11644473600000000 "
814 "WHERE rowid IN "
815 "(SELECT rowid FROM cookies WHERE "
816 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
817 #endif
818 ++cur_version;
819 meta_table_.SetVersionNumber(cur_version);
820 transaction.Commit();
823 if (cur_version == 4) {
824 const base::TimeTicks start_time = base::TimeTicks::Now();
825 sql::Transaction transaction(db_.get());
826 if (!transaction.Begin())
827 return false;
828 if (!db_->Execute("ALTER TABLE cookies "
829 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
830 !db_->Execute("ALTER TABLE cookies "
831 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
832 LOG(WARNING) << "Unable to update cookie database to version 5.";
833 return false;
835 ++cur_version;
836 meta_table_.SetVersionNumber(cur_version);
837 meta_table_.SetCompatibleVersionNumber(
838 std::min(cur_version, kCompatibleVersionNumber));
839 transaction.Commit();
840 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
841 base::TimeTicks::Now() - start_time);
844 if (cur_version == 5) {
845 const base::TimeTicks start_time = base::TimeTicks::Now();
846 sql::Transaction transaction(db_.get());
847 if (!transaction.Begin())
848 return false;
849 // Alter the table to add the priority column with a default value.
850 std::string stmt(base::StringPrintf(
851 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
852 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
853 if (!db_->Execute(stmt.c_str())) {
854 LOG(WARNING) << "Unable to update cookie database to version 6.";
855 return false;
857 ++cur_version;
858 meta_table_.SetVersionNumber(cur_version);
859 meta_table_.SetCompatibleVersionNumber(
860 std::min(cur_version, kCompatibleVersionNumber));
861 transaction.Commit();
862 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
863 base::TimeTicks::Now() - start_time);
866 if (cur_version == 6) {
867 const base::TimeTicks start_time = base::TimeTicks::Now();
868 sql::Transaction transaction(db_.get());
869 if (!transaction.Begin())
870 return false;
871 // Alter the table to add empty "encrypted value" column.
872 if (!db_->Execute("ALTER TABLE cookies "
873 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
874 LOG(WARNING) << "Unable to update cookie database to version 7.";
875 return false;
877 ++cur_version;
878 meta_table_.SetVersionNumber(cur_version);
879 meta_table_.SetCompatibleVersionNumber(
880 std::min(cur_version, kCompatibleVersionNumber));
881 transaction.Commit();
882 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
883 base::TimeTicks::Now() - start_time);
886 // Put future migration cases here.
888 if (cur_version < kCurrentVersionNumber) {
889 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
891 meta_table_.Reset();
892 db_.reset(new sql::Connection);
893 if (!base::DeleteFile(path_, false) ||
894 !db_->Open(path_) ||
895 !meta_table_.Init(
896 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
897 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
898 NOTREACHED() << "Unable to reset the cookie DB.";
899 meta_table_.Reset();
900 db_.reset();
901 return false;
905 return true;
908 void SQLitePersistentCookieStore::Backend::AddCookie(
909 const net::CanonicalCookie& cc) {
910 BatchOperation(PendingOperation::COOKIE_ADD, cc);
913 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
914 const net::CanonicalCookie& cc) {
915 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
918 void SQLitePersistentCookieStore::Backend::DeleteCookie(
919 const net::CanonicalCookie& cc) {
920 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
923 void SQLitePersistentCookieStore::Backend::BatchOperation(
924 PendingOperation::OperationType op,
925 const net::CanonicalCookie& cc) {
926 // Commit every 30 seconds.
927 static const int kCommitIntervalMs = 30 * 1000;
928 // Commit right away if we have more than 512 outstanding operations.
929 static const size_t kCommitAfterBatchSize = 512;
930 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
932 // We do a full copy of the cookie here, and hopefully just here.
933 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
935 PendingOperationsList::size_type num_pending;
937 base::AutoLock locked(lock_);
938 pending_.push_back(po.release());
939 num_pending = ++num_pending_;
942 if (num_pending == 1) {
943 // We've gotten our first entry for this batch, fire off the timer.
944 if (!background_task_runner_->PostDelayedTask(
945 FROM_HERE, base::Bind(&Backend::Commit, this),
946 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
947 NOTREACHED() << "background_task_runner_ is not running.";
949 } else if (num_pending == kCommitAfterBatchSize) {
950 // We've reached a big enough batch, fire off a commit now.
951 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
955 void SQLitePersistentCookieStore::Backend::Commit() {
956 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
958 PendingOperationsList ops;
960 base::AutoLock locked(lock_);
961 pending_.swap(ops);
962 num_pending_ = 0;
965 // Maybe an old timer fired or we are already Close()'ed.
966 if (!db_.get() || ops.empty())
967 return;
969 sql::Statement add_smt(db_->GetCachedStatement(SQL_FROM_HERE,
970 "INSERT INTO cookies (creation_utc, host_key, name, value, "
971 "encrypted_value, path, expires_utc, secure, httponly, last_access_utc, "
972 "has_expires, persistent, priority) "
973 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"));
974 if (!add_smt.is_valid())
975 return;
977 sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
978 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
979 if (!update_access_smt.is_valid())
980 return;
982 sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
983 "DELETE FROM cookies WHERE creation_utc=?"));
984 if (!del_smt.is_valid())
985 return;
987 sql::Transaction transaction(db_.get());
988 if (!transaction.Begin())
989 return;
991 for (PendingOperationsList::iterator it = ops.begin();
992 it != ops.end(); ++it) {
993 // Free the cookies as we commit them to the database.
994 scoped_ptr<PendingOperation> po(*it);
995 switch (po->op()) {
996 case PendingOperation::COOKIE_ADD:
997 cookies_per_origin_[
998 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
999 add_smt.Reset(true);
1000 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1001 add_smt.BindString(1, po->cc().Domain());
1002 add_smt.BindString(2, po->cc().Name());
1003 if (crypto_) {
1004 std::string encrypted_value;
1005 add_smt.BindCString(3, ""); // value
1006 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1007 // BindBlob() immediately makes an internal copy of the data.
1008 add_smt.BindBlob(4, encrypted_value.data(),
1009 static_cast<int>(encrypted_value.length()));
1010 } else {
1011 add_smt.BindString(3, po->cc().Value());
1012 add_smt.BindBlob(4, "", 0); // encrypted_value
1014 add_smt.BindString(5, po->cc().Path());
1015 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1016 add_smt.BindInt(7, po->cc().IsSecure());
1017 add_smt.BindInt(8, po->cc().IsHttpOnly());
1018 add_smt.BindInt64(9, po->cc().LastAccessDate().ToInternalValue());
1019 add_smt.BindInt(10, po->cc().IsPersistent());
1020 add_smt.BindInt(11, po->cc().IsPersistent());
1021 add_smt.BindInt(
1022 12, CookiePriorityToDBCookiePriority(po->cc().Priority()));
1023 if (!add_smt.Run())
1024 NOTREACHED() << "Could not add a cookie to the DB.";
1025 break;
1027 case PendingOperation::COOKIE_UPDATEACCESS:
1028 update_access_smt.Reset(true);
1029 update_access_smt.BindInt64(0,
1030 po->cc().LastAccessDate().ToInternalValue());
1031 update_access_smt.BindInt64(1,
1032 po->cc().CreationDate().ToInternalValue());
1033 if (!update_access_smt.Run())
1034 NOTREACHED() << "Could not update cookie last access time in the DB.";
1035 break;
1037 case PendingOperation::COOKIE_DELETE:
1038 cookies_per_origin_[
1039 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1040 del_smt.Reset(true);
1041 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1042 if (!del_smt.Run())
1043 NOTREACHED() << "Could not delete a cookie from the DB.";
1044 break;
1046 default:
1047 NOTREACHED();
1048 break;
1051 bool succeeded = transaction.Commit();
1052 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1053 succeeded ? 0 : 1, 2);
1056 void SQLitePersistentCookieStore::Backend::Flush(
1057 const base::Closure& callback) {
1058 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1059 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1061 if (!callback.is_null()) {
1062 // We want the completion task to run immediately after Commit() returns.
1063 // Posting it from here means there is less chance of another task getting
1064 // onto the message queue first, than if we posted it from Commit() itself.
1065 PostBackgroundTask(FROM_HERE, callback);
1069 // Fire off a close message to the background runner. We could still have a
1070 // pending commit timer or Load operations holding references on us, but if/when
1071 // this fires we will already have been cleaned up and it will be ignored.
1072 void SQLitePersistentCookieStore::Backend::Close() {
1073 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1074 InternalBackgroundClose();
1075 } else {
1076 // Must close the backend on the background runner.
1077 PostBackgroundTask(FROM_HERE,
1078 base::Bind(&Backend::InternalBackgroundClose, this));
1082 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1083 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1084 // Commit any pending operations
1085 Commit();
1087 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1088 special_storage_policy_->HasSessionOnlyOrigins()) {
1089 DeleteSessionCookiesOnShutdown();
1092 meta_table_.Reset();
1093 db_.reset();
1096 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1097 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1099 if (!db_)
1100 return;
1102 if (!special_storage_policy_.get())
1103 return;
1105 sql::Statement del_smt(db_->GetCachedStatement(
1106 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1107 if (!del_smt.is_valid()) {
1108 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1109 return;
1112 sql::Transaction transaction(db_.get());
1113 if (!transaction.Begin()) {
1114 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1115 return;
1118 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1119 it != cookies_per_origin_.end(); ++it) {
1120 if (it->second <= 0) {
1121 DCHECK_EQ(0, it->second);
1122 continue;
1124 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1125 it->first.second));
1126 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1127 continue;
1129 del_smt.Reset(true);
1130 del_smt.BindString(0, it->first.first);
1131 del_smt.BindInt(1, it->first.second);
1132 if (!del_smt.Run())
1133 NOTREACHED() << "Could not delete a cookie from the DB.";
1136 if (!transaction.Commit())
1137 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1140 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1141 int error,
1142 sql::Statement* stmt) {
1143 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1145 if (!sql::IsErrorCatastrophic(error))
1146 return;
1148 // TODO(shess): Running KillDatabase() multiple times should be
1149 // safe.
1150 if (corruption_detected_)
1151 return;
1153 corruption_detected_ = true;
1155 // Don't just do the close/delete here, as we are being called by |db| and
1156 // that seems dangerous.
1157 // TODO(shess): Consider just calling RazeAndClose() immediately.
1158 // db_ may not be safe to reset at this point, but RazeAndClose()
1159 // would cause the stack to unwind safely with errors.
1160 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1163 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1164 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1166 if (db_) {
1167 // This Backend will now be in-memory only. In a future run we will recreate
1168 // the database. Hopefully things go better then!
1169 bool success = db_->RazeAndClose();
1170 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1171 meta_table_.Reset();
1172 db_.reset();
1176 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1177 base::AutoLock locked(lock_);
1178 force_keep_session_state_ = true;
1181 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1182 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1183 if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0"))
1184 LOG(WARNING) << "Unable to delete session cookies.";
1187 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1188 const tracked_objects::Location& origin, const base::Closure& task) {
1189 if (!background_task_runner_->PostTask(origin, task)) {
1190 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1191 << " to background_task_runner_.";
1195 void SQLitePersistentCookieStore::Backend::PostClientTask(
1196 const tracked_objects::Location& origin, const base::Closure& task) {
1197 if (!client_task_runner_->PostTask(origin, task)) {
1198 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1199 << " to client_task_runner_.";
1203 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1204 const base::FilePath& path,
1205 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1206 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1207 bool restore_old_session_cookies,
1208 quota::SpecialStoragePolicy* special_storage_policy,
1209 CookieCryptoDelegate* crypto_delegate)
1210 : backend_(new Backend(path,
1211 client_task_runner,
1212 background_task_runner,
1213 restore_old_session_cookies,
1214 special_storage_policy,
1215 crypto_delegate)) {
1218 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1219 backend_->Load(loaded_callback);
1222 void SQLitePersistentCookieStore::LoadCookiesForKey(
1223 const std::string& key,
1224 const LoadedCallback& loaded_callback) {
1225 backend_->LoadCookiesForKey(key, loaded_callback);
1228 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) {
1229 backend_->AddCookie(cc);
1232 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1233 const net::CanonicalCookie& cc) {
1234 backend_->UpdateCookieAccessTime(cc);
1237 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) {
1238 backend_->DeleteCookie(cc);
1241 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1242 backend_->SetForceKeepSessionState();
1245 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1246 backend_->Flush(callback);
1249 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1250 backend_->Close();
1251 // We release our reference to the Backend, though it will probably still have
1252 // a reference if the background runner has not run Close() yet.
1255 CookieStoreConfig::CookieStoreConfig()
1256 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1257 crypto_delegate(NULL) {
1258 // Default to an in-memory cookie store.
1261 CookieStoreConfig::CookieStoreConfig(
1262 const base::FilePath& path,
1263 SessionCookieMode session_cookie_mode,
1264 quota::SpecialStoragePolicy* storage_policy,
1265 net::CookieMonsterDelegate* cookie_delegate)
1266 : path(path),
1267 session_cookie_mode(session_cookie_mode),
1268 storage_policy(storage_policy),
1269 cookie_delegate(cookie_delegate),
1270 crypto_delegate(NULL) {
1271 CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1274 CookieStoreConfig::~CookieStoreConfig() {
1277 net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1278 net::CookieMonster* cookie_monster = NULL;
1280 if (config.path.empty()) {
1281 // Empty path means in-memory store.
1282 cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate);
1283 } else {
1284 scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1285 config.client_task_runner;
1286 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1287 config.background_task_runner;
1289 if (!client_task_runner) {
1290 client_task_runner =
1291 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1294 if (!background_task_runner) {
1295 background_task_runner =
1296 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1297 BrowserThread::GetBlockingPool()->GetSequenceToken());
1300 SQLitePersistentCookieStore* persistent_store =
1301 new SQLitePersistentCookieStore(
1302 config.path,
1303 client_task_runner,
1304 background_task_runner,
1305 (config.session_cookie_mode ==
1306 CookieStoreConfig::RESTORED_SESSION_COOKIES),
1307 config.storage_policy,
1308 config.crypto_delegate);
1310 cookie_monster =
1311 new net::CookieMonster(persistent_store, config.cookie_delegate);
1312 if ((config.session_cookie_mode ==
1313 CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1314 (config.session_cookie_mode ==
1315 CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1316 cookie_monster->SetPersistSessionCookies(true);
1320 // In the case of Android WebView, the cookie store may be created
1321 // before the browser process fully initializes -- certainly before
1322 // the main loop ever runs. In this situation, the CommandLine singleton
1323 // will not have been set up. Android tests do not need file cookies
1324 // so always ignore them here.
1326 // TODO(ajwong): Remove the InitializedForCurrentProcess() check
1327 // once http://crbug.com/331424 is resolved.
1328 if (CommandLine::InitializedForCurrentProcess() &&
1329 CommandLine::ForCurrentProcess()->HasSwitch(
1330 switches::kEnableFileCookies)) {
1331 cookie_monster->SetEnableFileScheme(true);
1334 return cookie_monster;
1337 } // namespace content