IndexedDBFactory now ForceCloses databases.
[chromium-blink-merge.git] / content / browser / net / sqlite_persistent_cookie_store.cc
blob6386f85d3cb22b65f26e025c95ff76c24af35b91
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 scoped_ptr<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.Pass()) {}
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).
278 scoped_ptr<CookieCryptoDelegate> crypto_;
280 DISALLOW_COPY_AND_ASSIGN(Backend);
283 namespace {
285 // Version number of the database.
287 // Version 7 adds encrypted values. Old values will continue to be used but
288 // all new values written will be encrypted on selected operating systems. New
289 // records read by old clients will simply get an empty cookie value while old
290 // records read by new clients will continue to operate with the unencrypted
291 // version. New and old clients alike will always write/update records with
292 // what they support.
294 // Version 6 adds cookie priorities. This allows developers to influence the
295 // order in which cookies are evicted in order to meet domain cookie limits.
297 // Version 5 adds the columns has_expires and is_persistent, so that the
298 // database can store session cookies as well as persistent cookies. Databases
299 // of version 5 are incompatible with older versions of code. If a database of
300 // version 5 is read by older code, session cookies will be treated as normal
301 // cookies. Currently, these fields are written, but not read anymore.
303 // In version 4, we migrated the time epoch. If you open the DB with an older
304 // version on Mac or Linux, the times will look wonky, but the file will likely
305 // be usable. On Windows version 3 and 4 are the same.
307 // Version 3 updated the database to include the last access time, so we can
308 // expire them in decreasing order of use when we've reached the maximum
309 // number of cookies.
310 const int kCurrentVersionNumber = 7;
311 const int kCompatibleVersionNumber = 5;
313 // Possible values for the 'priority' column.
314 enum DBCookiePriority {
315 kCookiePriorityLow = 0,
316 kCookiePriorityMedium = 1,
317 kCookiePriorityHigh = 2,
320 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) {
321 switch (value) {
322 case net::COOKIE_PRIORITY_LOW:
323 return kCookiePriorityLow;
324 case net::COOKIE_PRIORITY_MEDIUM:
325 return kCookiePriorityMedium;
326 case net::COOKIE_PRIORITY_HIGH:
327 return kCookiePriorityHigh;
330 NOTREACHED();
331 return kCookiePriorityMedium;
334 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
335 switch (value) {
336 case kCookiePriorityLow:
337 return net::COOKIE_PRIORITY_LOW;
338 case kCookiePriorityMedium:
339 return net::COOKIE_PRIORITY_MEDIUM;
340 case kCookiePriorityHigh:
341 return net::COOKIE_PRIORITY_HIGH;
344 NOTREACHED();
345 return net::COOKIE_PRIORITY_DEFAULT;
348 // Increments a specified TimeDelta by the duration between this object's
349 // constructor and destructor. Not thread safe. Multiple instances may be
350 // created with the same delta instance as long as their lifetimes are nested.
351 // The shortest lived instances have no impact.
352 class IncrementTimeDelta {
353 public:
354 explicit IncrementTimeDelta(base::TimeDelta* delta) :
355 delta_(delta),
356 original_value_(*delta),
357 start_(base::Time::Now()) {}
359 ~IncrementTimeDelta() {
360 *delta_ = original_value_ + base::Time::Now() - start_;
363 private:
364 base::TimeDelta* delta_;
365 base::TimeDelta original_value_;
366 base::Time start_;
368 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
371 // Initializes the cookies table, returning true on success.
372 bool InitTable(sql::Connection* db) {
373 if (!db->DoesTableExist("cookies")) {
374 std::string stmt(base::StringPrintf(
375 "CREATE TABLE cookies ("
376 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
377 "host_key TEXT NOT NULL,"
378 "name TEXT NOT NULL,"
379 "value TEXT NOT NULL,"
380 "path TEXT NOT NULL,"
381 "expires_utc INTEGER NOT NULL,"
382 "secure INTEGER NOT NULL,"
383 "httponly INTEGER NOT NULL,"
384 "last_access_utc INTEGER NOT NULL, "
385 "has_expires INTEGER NOT NULL DEFAULT 1, "
386 "persistent INTEGER NOT NULL DEFAULT 1,"
387 "priority INTEGER NOT NULL DEFAULT %d,"
388 "encrypted_value BLOB DEFAULT '')",
389 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
390 if (!db->Execute(stmt.c_str()))
391 return false;
394 // Older code created an index on creation_utc, which is already
395 // primary key for the table.
396 if (!db->Execute("DROP INDEX IF EXISTS cookie_times"))
397 return false;
399 if (!db->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
400 return false;
402 return true;
405 } // namespace
407 void SQLitePersistentCookieStore::Backend::Load(
408 const LoadedCallback& loaded_callback) {
409 // This function should be called only once per instance.
410 DCHECK(!db_.get());
411 PostBackgroundTask(FROM_HERE, base::Bind(
412 &Backend::LoadAndNotifyInBackground, this,
413 loaded_callback, base::Time::Now()));
416 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
417 const std::string& key,
418 const LoadedCallback& loaded_callback) {
420 base::AutoLock locked(metrics_lock_);
421 if (num_priority_waiting_ == 0)
422 current_priority_wait_start_ = base::Time::Now();
423 num_priority_waiting_++;
424 total_priority_requests_++;
427 PostBackgroundTask(FROM_HERE, base::Bind(
428 &Backend::LoadKeyAndNotifyInBackground,
429 this, key, loaded_callback, base::Time::Now()));
432 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
433 const LoadedCallback& loaded_callback, const base::Time& posted_at) {
434 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
435 IncrementTimeDelta increment(&cookie_load_duration_);
437 UMA_HISTOGRAM_CUSTOM_TIMES(
438 "Cookie.TimeLoadDBQueueWait",
439 base::Time::Now() - posted_at,
440 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
441 50);
443 if (!InitializeDatabase()) {
444 PostClientTask(FROM_HERE, base::Bind(
445 &Backend::CompleteLoadInForeground, this, loaded_callback, false));
446 } else {
447 ChainLoadCookies(loaded_callback);
451 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
452 const std::string& key,
453 const LoadedCallback& loaded_callback,
454 const base::Time& posted_at) {
455 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
456 IncrementTimeDelta increment(&cookie_load_duration_);
458 UMA_HISTOGRAM_CUSTOM_TIMES(
459 "Cookie.TimeKeyLoadDBQueueWait",
460 base::Time::Now() - posted_at,
461 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
462 50);
464 bool success = false;
465 if (InitializeDatabase()) {
466 std::map<std::string, std::set<std::string> >::iterator
467 it = keys_to_load_.find(key);
468 if (it != keys_to_load_.end()) {
469 success = LoadCookiesForDomains(it->second);
470 keys_to_load_.erase(it);
471 } else {
472 success = true;
476 PostClientTask(FROM_HERE, base::Bind(
477 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
478 this, loaded_callback, success));
481 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
482 const LoadedCallback& loaded_callback,
483 bool load_success) {
484 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
486 Notify(loaded_callback, load_success);
489 base::AutoLock locked(metrics_lock_);
490 num_priority_waiting_--;
491 if (num_priority_waiting_ == 0) {
492 priority_wait_duration_ +=
493 base::Time::Now() - current_priority_wait_start_;
499 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
500 UMA_HISTOGRAM_CUSTOM_TIMES(
501 "Cookie.TimeLoad",
502 cookie_load_duration_,
503 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
504 50);
507 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
508 PostBackgroundTask(FROM_HERE, base::Bind(
509 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground, this));
512 base::AutoLock locked(metrics_lock_);
513 UMA_HISTOGRAM_CUSTOM_TIMES(
514 "Cookie.PriorityBlockingTime",
515 priority_wait_duration_,
516 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
517 50);
519 UMA_HISTOGRAM_COUNTS_100(
520 "Cookie.PriorityLoadCount",
521 total_priority_requests_);
523 UMA_HISTOGRAM_COUNTS_10000(
524 "Cookie.NumberOfLoadedCookies",
525 num_cookies_read_);
529 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
530 const LoadedCallback& loaded_callback, bool load_success) {
531 Notify(loaded_callback, load_success);
533 if (load_success)
534 ReportMetrics();
537 void SQLitePersistentCookieStore::Backend::Notify(
538 const LoadedCallback& loaded_callback,
539 bool load_success) {
540 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
542 std::vector<net::CanonicalCookie*> cookies;
544 base::AutoLock locked(lock_);
545 cookies.swap(cookies_);
548 loaded_callback.Run(cookies);
551 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
552 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
554 if (initialized_ || corruption_detected_) {
555 // Return false if we were previously initialized but the DB has since been
556 // closed, or if corruption caused a database reset during initialization.
557 return db_ != NULL;
560 base::Time start = base::Time::Now();
562 const base::FilePath dir = path_.DirName();
563 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
564 return false;
567 int64 db_size = 0;
568 if (base::GetFileSize(path_, &db_size))
569 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024 );
571 db_.reset(new sql::Connection);
572 db_->set_histogram_tag("Cookie");
574 // Unretained to avoid a ref loop with |db_|.
575 db_->set_error_callback(
576 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
577 base::Unretained(this)));
579 if (!db_->Open(path_)) {
580 NOTREACHED() << "Unable to open cookie DB.";
581 if (corruption_detected_)
582 db_->Raze();
583 meta_table_.Reset();
584 db_.reset();
585 return false;
588 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
589 NOTREACHED() << "Unable to open cookie DB.";
590 if (corruption_detected_)
591 db_->Raze();
592 meta_table_.Reset();
593 db_.reset();
594 return false;
597 UMA_HISTOGRAM_CUSTOM_TIMES(
598 "Cookie.TimeInitializeDB",
599 base::Time::Now() - start,
600 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
601 50);
603 start = base::Time::Now();
605 // Retrieve all the domains
606 sql::Statement smt(db_->GetUniqueStatement(
607 "SELECT DISTINCT host_key FROM cookies"));
609 if (!smt.is_valid()) {
610 if (corruption_detected_)
611 db_->Raze();
612 meta_table_.Reset();
613 db_.reset();
614 return false;
617 std::vector<std::string> host_keys;
618 while (smt.Step())
619 host_keys.push_back(smt.ColumnString(0));
621 UMA_HISTOGRAM_CUSTOM_TIMES(
622 "Cookie.TimeLoadDomains",
623 base::Time::Now() - start,
624 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
625 50);
627 base::Time start_parse = base::Time::Now();
629 // Build a map of domain keys (always eTLD+1) to domains.
630 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
631 const std::string& domain = host_keys[idx];
632 std::string key =
633 net::registry_controlled_domains::GetDomainAndRegistry(
634 domain,
635 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
637 keys_to_load_[key].insert(domain);
640 UMA_HISTOGRAM_CUSTOM_TIMES(
641 "Cookie.TimeParseDomains",
642 base::Time::Now() - start_parse,
643 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
644 50);
646 UMA_HISTOGRAM_CUSTOM_TIMES(
647 "Cookie.TimeInitializeDomainMap",
648 base::Time::Now() - start,
649 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
650 50);
652 initialized_ = true;
653 return true;
656 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
657 const LoadedCallback& loaded_callback) {
658 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
659 IncrementTimeDelta increment(&cookie_load_duration_);
661 bool load_success = true;
663 if (!db_) {
664 // Close() has been called on this store.
665 load_success = false;
666 } else if (keys_to_load_.size() > 0) {
667 // Load cookies for the first domain key.
668 std::map<std::string, std::set<std::string> >::iterator
669 it = keys_to_load_.begin();
670 load_success = LoadCookiesForDomains(it->second);
671 keys_to_load_.erase(it);
674 // If load is successful and there are more domain keys to be loaded,
675 // then post a background task to continue chain-load;
676 // Otherwise notify on client runner.
677 if (load_success && keys_to_load_.size() > 0) {
678 PostBackgroundTask(FROM_HERE, base::Bind(
679 &Backend::ChainLoadCookies, this, loaded_callback));
680 } else {
681 PostClientTask(FROM_HERE, base::Bind(
682 &Backend::CompleteLoadInForeground, this,
683 loaded_callback, load_success));
684 if (load_success && !restore_old_session_cookies_)
685 DeleteSessionCookiesOnStartup();
689 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
690 const std::set<std::string>& domains) {
691 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
693 sql::Statement smt;
694 if (restore_old_session_cookies_) {
695 smt.Assign(db_->GetCachedStatement(
696 SQL_FROM_HERE,
697 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
698 "expires_utc, secure, httponly, last_access_utc, has_expires, "
699 "persistent, priority FROM cookies WHERE host_key = ?"));
700 } else {
701 smt.Assign(db_->GetCachedStatement(
702 SQL_FROM_HERE,
703 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
704 "expires_utc, secure, httponly, last_access_utc, has_expires, "
705 "persistent, priority FROM cookies WHERE host_key = ? "
706 "AND persistent = 1"));
708 if (!smt.is_valid()) {
709 smt.Clear(); // Disconnect smt_ref from db_.
710 meta_table_.Reset();
711 db_.reset();
712 return false;
715 std::vector<net::CanonicalCookie*> cookies;
716 std::set<std::string>::const_iterator it = domains.begin();
717 for (; it != domains.end(); ++it) {
718 smt.BindString(0, *it);
719 while (smt.Step()) {
720 std::string value;
721 std::string encrypted_value = smt.ColumnString(4);
722 if (!encrypted_value.empty() && crypto_.get()) {
723 crypto_->DecryptString(encrypted_value, &value);
724 } else {
725 DCHECK(encrypted_value.empty());
726 value = smt.ColumnString(3);
728 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie(
729 // The "source" URL is not used with persisted cookies.
730 GURL(), // Source
731 smt.ColumnString(2), // name
732 value, // value
733 smt.ColumnString(1), // domain
734 smt.ColumnString(5), // path
735 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
736 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
737 Time::FromInternalValue(smt.ColumnInt64(9)), // last_access_utc
738 smt.ColumnInt(7) != 0, // secure
739 smt.ColumnInt(8) != 0, // httponly
740 DBCookiePriorityToCookiePriority(
741 static_cast<DBCookiePriority>(smt.ColumnInt(12))))); // priority
742 DLOG_IF(WARNING,
743 cc->CreationDate() > Time::Now()) << L"CreationDate too recent";
744 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
745 cookies.push_back(cc.release());
746 ++num_cookies_read_;
748 smt.Reset(true);
751 base::AutoLock locked(lock_);
752 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
754 return true;
757 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
758 // Version check.
759 if (!meta_table_.Init(
760 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
761 return false;
764 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
765 LOG(WARNING) << "Cookie database is too new.";
766 return false;
769 int cur_version = meta_table_.GetVersionNumber();
770 if (cur_version == 2) {
771 sql::Transaction transaction(db_.get());
772 if (!transaction.Begin())
773 return false;
774 if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
775 "INTEGER DEFAULT 0") ||
776 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
777 LOG(WARNING) << "Unable to update cookie database to version 3.";
778 return false;
780 ++cur_version;
781 meta_table_.SetVersionNumber(cur_version);
782 meta_table_.SetCompatibleVersionNumber(
783 std::min(cur_version, kCompatibleVersionNumber));
784 transaction.Commit();
787 if (cur_version == 3) {
788 // The time epoch changed for Mac & Linux in this version to match Windows.
789 // This patch came after the main epoch change happened, so some
790 // developers have "good" times for cookies added by the more recent
791 // versions. So we have to be careful to only update times that are under
792 // the old system (which will appear to be from before 1970 in the new
793 // system). The magic number used below is 1970 in our time units.
794 sql::Transaction transaction(db_.get());
795 transaction.Begin();
796 #if !defined(OS_WIN)
797 ignore_result(db_->Execute(
798 "UPDATE cookies "
799 "SET creation_utc = creation_utc + 11644473600000000 "
800 "WHERE rowid IN "
801 "(SELECT rowid FROM cookies WHERE "
802 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
803 ignore_result(db_->Execute(
804 "UPDATE cookies "
805 "SET expires_utc = expires_utc + 11644473600000000 "
806 "WHERE rowid IN "
807 "(SELECT rowid FROM cookies WHERE "
808 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
809 ignore_result(db_->Execute(
810 "UPDATE cookies "
811 "SET last_access_utc = last_access_utc + 11644473600000000 "
812 "WHERE rowid IN "
813 "(SELECT rowid FROM cookies WHERE "
814 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
815 #endif
816 ++cur_version;
817 meta_table_.SetVersionNumber(cur_version);
818 transaction.Commit();
821 if (cur_version == 4) {
822 const base::TimeTicks start_time = base::TimeTicks::Now();
823 sql::Transaction transaction(db_.get());
824 if (!transaction.Begin())
825 return false;
826 if (!db_->Execute("ALTER TABLE cookies "
827 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
828 !db_->Execute("ALTER TABLE cookies "
829 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
830 LOG(WARNING) << "Unable to update cookie database to version 5.";
831 return false;
833 ++cur_version;
834 meta_table_.SetVersionNumber(cur_version);
835 meta_table_.SetCompatibleVersionNumber(
836 std::min(cur_version, kCompatibleVersionNumber));
837 transaction.Commit();
838 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
839 base::TimeTicks::Now() - start_time);
842 if (cur_version == 5) {
843 const base::TimeTicks start_time = base::TimeTicks::Now();
844 sql::Transaction transaction(db_.get());
845 if (!transaction.Begin())
846 return false;
847 // Alter the table to add the priority column with a default value.
848 std::string stmt(base::StringPrintf(
849 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
850 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
851 if (!db_->Execute(stmt.c_str())) {
852 LOG(WARNING) << "Unable to update cookie database to version 6.";
853 return false;
855 ++cur_version;
856 meta_table_.SetVersionNumber(cur_version);
857 meta_table_.SetCompatibleVersionNumber(
858 std::min(cur_version, kCompatibleVersionNumber));
859 transaction.Commit();
860 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
861 base::TimeTicks::Now() - start_time);
864 if (cur_version == 6) {
865 const base::TimeTicks start_time = base::TimeTicks::Now();
866 sql::Transaction transaction(db_.get());
867 if (!transaction.Begin())
868 return false;
869 // Alter the table to add empty "encrypted value" column.
870 if (!db_->Execute("ALTER TABLE cookies "
871 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
872 LOG(WARNING) << "Unable to update cookie database to version 7.";
873 return false;
875 ++cur_version;
876 meta_table_.SetVersionNumber(cur_version);
877 meta_table_.SetCompatibleVersionNumber(
878 std::min(cur_version, kCompatibleVersionNumber));
879 transaction.Commit();
880 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
881 base::TimeTicks::Now() - start_time);
884 // Put future migration cases here.
886 if (cur_version < kCurrentVersionNumber) {
887 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
889 meta_table_.Reset();
890 db_.reset(new sql::Connection);
891 if (!base::DeleteFile(path_, false) ||
892 !db_->Open(path_) ||
893 !meta_table_.Init(
894 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
895 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
896 NOTREACHED() << "Unable to reset the cookie DB.";
897 meta_table_.Reset();
898 db_.reset();
899 return false;
903 return true;
906 void SQLitePersistentCookieStore::Backend::AddCookie(
907 const net::CanonicalCookie& cc) {
908 BatchOperation(PendingOperation::COOKIE_ADD, cc);
911 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
912 const net::CanonicalCookie& cc) {
913 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
916 void SQLitePersistentCookieStore::Backend::DeleteCookie(
917 const net::CanonicalCookie& cc) {
918 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
921 void SQLitePersistentCookieStore::Backend::BatchOperation(
922 PendingOperation::OperationType op,
923 const net::CanonicalCookie& cc) {
924 // Commit every 30 seconds.
925 static const int kCommitIntervalMs = 30 * 1000;
926 // Commit right away if we have more than 512 outstanding operations.
927 static const size_t kCommitAfterBatchSize = 512;
928 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
930 // We do a full copy of the cookie here, and hopefully just here.
931 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
933 PendingOperationsList::size_type num_pending;
935 base::AutoLock locked(lock_);
936 pending_.push_back(po.release());
937 num_pending = ++num_pending_;
940 if (num_pending == 1) {
941 // We've gotten our first entry for this batch, fire off the timer.
942 if (!background_task_runner_->PostDelayedTask(
943 FROM_HERE, base::Bind(&Backend::Commit, this),
944 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
945 NOTREACHED() << "background_task_runner_ is not running.";
947 } else if (num_pending == kCommitAfterBatchSize) {
948 // We've reached a big enough batch, fire off a commit now.
949 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
953 void SQLitePersistentCookieStore::Backend::Commit() {
954 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
956 PendingOperationsList ops;
958 base::AutoLock locked(lock_);
959 pending_.swap(ops);
960 num_pending_ = 0;
963 // Maybe an old timer fired or we are already Close()'ed.
964 if (!db_.get() || ops.empty())
965 return;
967 sql::Statement add_smt(db_->GetCachedStatement(SQL_FROM_HERE,
968 "INSERT INTO cookies (creation_utc, host_key, name, value, "
969 "encrypted_value, path, expires_utc, secure, httponly, last_access_utc, "
970 "has_expires, persistent, priority) "
971 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"));
972 if (!add_smt.is_valid())
973 return;
975 sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
976 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
977 if (!update_access_smt.is_valid())
978 return;
980 sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
981 "DELETE FROM cookies WHERE creation_utc=?"));
982 if (!del_smt.is_valid())
983 return;
985 sql::Transaction transaction(db_.get());
986 if (!transaction.Begin())
987 return;
989 for (PendingOperationsList::iterator it = ops.begin();
990 it != ops.end(); ++it) {
991 // Free the cookies as we commit them to the database.
992 scoped_ptr<PendingOperation> po(*it);
993 switch (po->op()) {
994 case PendingOperation::COOKIE_ADD:
995 cookies_per_origin_[
996 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
997 add_smt.Reset(true);
998 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
999 add_smt.BindString(1, po->cc().Domain());
1000 add_smt.BindString(2, po->cc().Name());
1001 if (crypto_.get()) {
1002 std::string encrypted_value;
1003 add_smt.BindCString(3, ""); // value
1004 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1005 // BindBlob() immediately makes an internal copy of the data.
1006 add_smt.BindBlob(4, encrypted_value.data(),
1007 static_cast<int>(encrypted_value.length()));
1008 } else {
1009 add_smt.BindString(3, po->cc().Value());
1010 add_smt.BindBlob(4, "", 0); // encrypted_value
1012 add_smt.BindString(5, po->cc().Path());
1013 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1014 add_smt.BindInt(7, po->cc().IsSecure());
1015 add_smt.BindInt(8, po->cc().IsHttpOnly());
1016 add_smt.BindInt64(9, po->cc().LastAccessDate().ToInternalValue());
1017 add_smt.BindInt(10, po->cc().IsPersistent());
1018 add_smt.BindInt(11, po->cc().IsPersistent());
1019 add_smt.BindInt(
1020 12, CookiePriorityToDBCookiePriority(po->cc().Priority()));
1021 if (!add_smt.Run())
1022 NOTREACHED() << "Could not add a cookie to the DB.";
1023 break;
1025 case PendingOperation::COOKIE_UPDATEACCESS:
1026 update_access_smt.Reset(true);
1027 update_access_smt.BindInt64(0,
1028 po->cc().LastAccessDate().ToInternalValue());
1029 update_access_smt.BindInt64(1,
1030 po->cc().CreationDate().ToInternalValue());
1031 if (!update_access_smt.Run())
1032 NOTREACHED() << "Could not update cookie last access time in the DB.";
1033 break;
1035 case PendingOperation::COOKIE_DELETE:
1036 cookies_per_origin_[
1037 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1038 del_smt.Reset(true);
1039 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1040 if (!del_smt.Run())
1041 NOTREACHED() << "Could not delete a cookie from the DB.";
1042 break;
1044 default:
1045 NOTREACHED();
1046 break;
1049 bool succeeded = transaction.Commit();
1050 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1051 succeeded ? 0 : 1, 2);
1054 void SQLitePersistentCookieStore::Backend::Flush(
1055 const base::Closure& callback) {
1056 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1057 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1059 if (!callback.is_null()) {
1060 // We want the completion task to run immediately after Commit() returns.
1061 // Posting it from here means there is less chance of another task getting
1062 // onto the message queue first, than if we posted it from Commit() itself.
1063 PostBackgroundTask(FROM_HERE, callback);
1067 // Fire off a close message to the background runner. We could still have a
1068 // pending commit timer or Load operations holding references on us, but if/when
1069 // this fires we will already have been cleaned up and it will be ignored.
1070 void SQLitePersistentCookieStore::Backend::Close() {
1071 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1072 InternalBackgroundClose();
1073 } else {
1074 // Must close the backend on the background runner.
1075 PostBackgroundTask(FROM_HERE,
1076 base::Bind(&Backend::InternalBackgroundClose, this));
1080 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1081 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1082 // Commit any pending operations
1083 Commit();
1085 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1086 special_storage_policy_->HasSessionOnlyOrigins()) {
1087 DeleteSessionCookiesOnShutdown();
1090 meta_table_.Reset();
1091 db_.reset();
1094 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1095 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1097 if (!db_)
1098 return;
1100 if (!special_storage_policy_.get())
1101 return;
1103 sql::Statement del_smt(db_->GetCachedStatement(
1104 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1105 if (!del_smt.is_valid()) {
1106 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1107 return;
1110 sql::Transaction transaction(db_.get());
1111 if (!transaction.Begin()) {
1112 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1113 return;
1116 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1117 it != cookies_per_origin_.end(); ++it) {
1118 if (it->second <= 0) {
1119 DCHECK_EQ(0, it->second);
1120 continue;
1122 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1123 it->first.second));
1124 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1125 continue;
1127 del_smt.Reset(true);
1128 del_smt.BindString(0, it->first.first);
1129 del_smt.BindInt(1, it->first.second);
1130 if (!del_smt.Run())
1131 NOTREACHED() << "Could not delete a cookie from the DB.";
1134 if (!transaction.Commit())
1135 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1138 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1139 int error,
1140 sql::Statement* stmt) {
1141 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1143 if (!sql::IsErrorCatastrophic(error))
1144 return;
1146 // TODO(shess): Running KillDatabase() multiple times should be
1147 // safe.
1148 if (corruption_detected_)
1149 return;
1151 corruption_detected_ = true;
1153 // Don't just do the close/delete here, as we are being called by |db| and
1154 // that seems dangerous.
1155 // TODO(shess): Consider just calling RazeAndClose() immediately.
1156 // db_ may not be safe to reset at this point, but RazeAndClose()
1157 // would cause the stack to unwind safely with errors.
1158 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1161 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1162 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1164 if (db_) {
1165 // This Backend will now be in-memory only. In a future run we will recreate
1166 // the database. Hopefully things go better then!
1167 bool success = db_->RazeAndClose();
1168 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1169 meta_table_.Reset();
1170 db_.reset();
1174 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1175 base::AutoLock locked(lock_);
1176 force_keep_session_state_ = true;
1179 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1180 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1181 if (!db_->Execute("DELETE FROM cookies WHERE persistent == 0"))
1182 LOG(WARNING) << "Unable to delete session cookies.";
1185 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1186 const tracked_objects::Location& origin, const base::Closure& task) {
1187 if (!background_task_runner_->PostTask(origin, task)) {
1188 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1189 << " to background_task_runner_.";
1193 void SQLitePersistentCookieStore::Backend::PostClientTask(
1194 const tracked_objects::Location& origin, const base::Closure& task) {
1195 if (!client_task_runner_->PostTask(origin, task)) {
1196 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1197 << " to client_task_runner_.";
1201 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1202 const base::FilePath& path,
1203 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1204 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1205 bool restore_old_session_cookies,
1206 quota::SpecialStoragePolicy* special_storage_policy,
1207 scoped_ptr<CookieCryptoDelegate> crypto_delegate)
1208 : backend_(new Backend(path,
1209 client_task_runner,
1210 background_task_runner,
1211 restore_old_session_cookies,
1212 special_storage_policy,
1213 crypto_delegate.Pass())) {
1216 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1217 backend_->Load(loaded_callback);
1220 void SQLitePersistentCookieStore::LoadCookiesForKey(
1221 const std::string& key,
1222 const LoadedCallback& loaded_callback) {
1223 backend_->LoadCookiesForKey(key, loaded_callback);
1226 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) {
1227 backend_->AddCookie(cc);
1230 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1231 const net::CanonicalCookie& cc) {
1232 backend_->UpdateCookieAccessTime(cc);
1235 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) {
1236 backend_->DeleteCookie(cc);
1239 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1240 backend_->SetForceKeepSessionState();
1243 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1244 backend_->Flush(callback);
1247 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1248 backend_->Close();
1249 // We release our reference to the Backend, though it will probably still have
1250 // a reference if the background runner has not run Close() yet.
1253 net::CookieStore* CreatePersistentCookieStore(
1254 const base::FilePath& path,
1255 bool restore_old_session_cookies,
1256 quota::SpecialStoragePolicy* storage_policy,
1257 net::CookieMonster::Delegate* cookie_monster_delegate,
1258 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1259 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1260 scoped_ptr<CookieCryptoDelegate> crypto_delegate) {
1261 SQLitePersistentCookieStore* persistent_store =
1262 new SQLitePersistentCookieStore(
1263 path,
1264 client_task_runner,
1265 background_task_runner,
1266 restore_old_session_cookies,
1267 storage_policy,
1268 crypto_delegate.Pass());
1270 net::CookieMonster* cookie_monster =
1271 new net::CookieMonster(persistent_store, cookie_monster_delegate);
1273 // In the case of Android WebView, the cookie store may be created
1274 // before the browser process fully initializes -- certainly before
1275 // the main loop ever runs. In this situation, the CommandLine singleton
1276 // will not have been set up. Android tests do not need file cookies
1277 // so always ignore them here.
1279 // TODO(ajwong): Remove the InitializedForCurrentProcess() check
1280 // once http://crbug.com/331424 is resolved.
1281 if (CommandLine::InitializedForCurrentProcess() &&
1282 CommandLine::ForCurrentProcess()->HasSwitch(
1283 switches::kEnableFileCookies)) {
1284 cookie_monster->SetEnableFileScheme(true);
1287 return cookie_monster;
1290 net::CookieStore* CreatePersistentCookieStore(
1291 const base::FilePath& path,
1292 bool restore_old_session_cookies,
1293 quota::SpecialStoragePolicy* storage_policy,
1294 net::CookieMonster::Delegate* cookie_monster_delegate,
1295 scoped_ptr<CookieCryptoDelegate> crypto_delegate) {
1296 return CreatePersistentCookieStore(
1297 path,
1298 restore_old_session_cookies,
1299 storage_policy,
1300 cookie_monster_delegate,
1301 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
1302 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1303 BrowserThread::GetBlockingPool()->GetSequenceToken()),
1304 crypto_delegate.Pass());
1307 net::CookieStore* CreateInMemoryCookieStore(
1308 net::CookieMonster::Delegate* cookie_monster_delegate) {
1309 net::CookieMonster* cookie_monster =
1310 new net::CookieMonster(NULL, cookie_monster_delegate);
1311 if (CommandLine::InitializedForCurrentProcess() &&
1312 CommandLine::ForCurrentProcess()->HasSwitch(
1313 switches::kEnableFileCookies)) {
1314 cookie_monster->SetEnableFileScheme(true);
1316 return cookie_monster;
1319 } // namespace content