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"
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/memory/ref_counted.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/sequenced_task_runner.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/synchronization/lock.h"
28 #include "base/threading/sequenced_worker_pool.h"
29 #include "base/time/time.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/cookie_crypto_delegate.h"
32 #include "content/public/browser/cookie_store_factory.h"
33 #include "content/public/common/content_switches.h"
34 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
35 #include "net/cookies/canonical_cookie.h"
36 #include "net/cookies/cookie_constants.h"
37 #include "net/cookies/cookie_util.h"
38 #include "sql/error_delegate_util.h"
39 #include "sql/meta_table.h"
40 #include "sql/statement.h"
41 #include "sql/transaction.h"
42 #include "storage/browser/quota/special_storage_policy.h"
43 #include "third_party/sqlite/sqlite3.h"
50 // The persistent cookie store is loaded into memory on eTLD at a time. This
51 // variable controls the delay between loading eTLDs, so as to not overload the
52 // CPU or I/O with these low priority requests immediately after start up.
53 const int kLoadDelayMilliseconds
= 200;
59 // This class is designed to be shared between any client thread and the
60 // background task runner. It batches operations and commits them on a timer.
62 // SQLitePersistentCookieStore::Load is called to load all cookies. It
63 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
64 // task to the background runner. This task calls Backend::ChainLoadCookies(),
65 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
66 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
67 // posted to the client runner, which notifies the caller of
68 // SQLitePersistentCookieStore::Load that the load is complete.
70 // If a priority load request is invoked via SQLitePersistentCookieStore::
71 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
72 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
73 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
74 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
75 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
77 // Subsequent to loading, mutations may be queued by any thread using
78 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
79 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
80 // whichever occurs first.
81 class SQLitePersistentCookieStore::Backend
82 : public base::RefCountedThreadSafe
<SQLitePersistentCookieStore::Backend
> {
85 const base::FilePath
& path
,
86 const scoped_refptr
<base::SequencedTaskRunner
>& client_task_runner
,
87 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
,
88 bool restore_old_session_cookies
,
89 storage::SpecialStoragePolicy
* special_storage_policy
,
90 CookieCryptoDelegate
* crypto_delegate
)
93 force_keep_session_state_(false),
95 corruption_detected_(false),
96 restore_old_session_cookies_(restore_old_session_cookies
),
97 special_storage_policy_(special_storage_policy
),
99 client_task_runner_(client_task_runner
),
100 background_task_runner_(background_task_runner
),
101 num_priority_waiting_(0),
102 total_priority_requests_(0),
103 crypto_(crypto_delegate
) {}
105 // Creates or loads the SQLite database.
106 void Load(const LoadedCallback
& loaded_callback
);
108 // Loads cookies for the domain key (eTLD+1).
109 void LoadCookiesForKey(const std::string
& domain
,
110 const LoadedCallback
& loaded_callback
);
112 // Steps through all results of |smt|, makes a cookie from each, and adds the
113 // cookie to |cookies|. This method also updates |cookies_per_origin_| and
114 // |num_cookies_read_|.
115 void MakeCookiesFromSQLStatement(std::vector
<net::CanonicalCookie
*>* cookies
,
116 sql::Statement
* statement
);
118 // Batch a cookie addition.
119 void AddCookie(const net::CanonicalCookie
& cc
);
121 // Batch a cookie access time update.
122 void UpdateCookieAccessTime(const net::CanonicalCookie
& cc
);
124 // Batch a cookie deletion.
125 void DeleteCookie(const net::CanonicalCookie
& cc
);
127 // Commit pending operations as soon as possible.
128 void Flush(const base::Closure
& callback
);
130 // Commit any pending operations and close the database. This must be called
131 // before the object is destructed.
134 void SetForceKeepSessionState();
137 friend class base::RefCountedThreadSafe
<SQLitePersistentCookieStore::Backend
>;
139 // You should call Close() before destructing this object.
141 DCHECK(!db_
.get()) << "Close should have already been called.";
142 DCHECK(num_pending_
== 0 && pending_
.empty());
145 // Database upgrade statements.
146 bool EnsureDatabaseVersion();
148 class PendingOperation
{
156 PendingOperation(OperationType op
, const net::CanonicalCookie
& cc
)
157 : op_(op
), cc_(cc
) { }
159 OperationType
op() const { return op_
; }
160 const net::CanonicalCookie
& cc() const { return cc_
; }
164 net::CanonicalCookie cc_
;
168 // Creates or loads the SQLite database on background runner.
169 void LoadAndNotifyInBackground(const LoadedCallback
& loaded_callback
,
170 const base::Time
& posted_at
);
172 // Loads cookies for the domain key (eTLD+1) on background runner.
173 void LoadKeyAndNotifyInBackground(const std::string
& domains
,
174 const LoadedCallback
& loaded_callback
,
175 const base::Time
& posted_at
);
177 // Notifies the CookieMonster when loading completes for a specific domain key
178 // or for all domain keys. Triggers the callback and passes it all cookies
179 // that have been loaded from DB since last IO notification.
180 void Notify(const LoadedCallback
& loaded_callback
, bool load_success
);
182 // Sends notification when the entire store is loaded, and reports metrics
183 // for the total time to load and aggregated results from any priority loads
185 void CompleteLoadInForeground(const LoadedCallback
& loaded_callback
,
188 // Sends notification when a single priority load completes. Updates priority
189 // load metric data. The data is sent only after the final load completes.
190 void CompleteLoadForKeyInForeground(const LoadedCallback
& loaded_callback
,
193 // Sends all metrics, including posting a ReportMetricsInBackground task.
194 // Called after all priority and regular loading is complete.
195 void ReportMetrics();
197 // Sends background-runner owned metrics (i.e., the combined duration of all
199 void ReportMetricsInBackground();
201 // Initialize the data base.
202 bool InitializeDatabase();
204 // Loads cookies for the next domain key from the DB, then either reschedules
205 // itself or schedules the provided callback to run on the client runner (if
206 // all domains are loaded).
207 void ChainLoadCookies(const LoadedCallback
& loaded_callback
);
209 // Load all cookies for a set of domains/hosts
210 bool LoadCookiesForDomains(const std::set
<std::string
>& key
);
212 // Batch a cookie operation (add or delete)
213 void BatchOperation(PendingOperation::OperationType op
,
214 const net::CanonicalCookie
& cc
);
215 // Commit our pending operations to the database.
217 // Close() executed on the background runner.
218 void InternalBackgroundClose();
220 void DeleteSessionCookiesOnStartup();
222 void DeleteSessionCookiesOnShutdown();
224 void DatabaseErrorCallback(int error
, sql::Statement
* stmt
);
227 void PostBackgroundTask(const tracked_objects::Location
& origin
,
228 const base::Closure
& task
);
229 void PostClientTask(const tracked_objects::Location
& origin
,
230 const base::Closure
& task
);
232 // Shared code between the different load strategies to be used after all
233 // cookies have been loaded.
234 void FinishedLoadingCookies(const LoadedCallback
& loaded_callback
,
237 base::FilePath path_
;
238 scoped_ptr
<sql::Connection
> db_
;
239 sql::MetaTable meta_table_
;
241 typedef std::list
<PendingOperation
*> PendingOperationsList
;
242 PendingOperationsList pending_
;
243 PendingOperationsList::size_type num_pending_
;
244 // True if the persistent store should skip delete on exit rules.
245 bool force_keep_session_state_
;
246 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
249 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
250 // the number of messages sent to the client runner. Sent back in response to
251 // individual load requests for domain keys or when all loading completes.
252 std::vector
<net::CanonicalCookie
*> cookies_
;
254 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
255 std::map
<std::string
, std::set
<std::string
> > keys_to_load_
;
257 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
259 typedef std::pair
<std::string
, bool> CookieOrigin
;
260 typedef std::map
<CookieOrigin
, int> CookiesPerOriginMap
;
261 CookiesPerOriginMap cookies_per_origin_
;
263 // Indicates if DB has been initialized.
266 // Indicates if the kill-database callback has been scheduled.
267 bool corruption_detected_
;
269 // If false, we should filter out session cookies when reading the DB.
270 bool restore_old_session_cookies_
;
272 // Policy defining what data is deleted on shutdown.
273 scoped_refptr
<storage::SpecialStoragePolicy
> special_storage_policy_
;
275 // The cumulative time spent loading the cookies on the background runner.
276 // Incremented and reported from the background runner.
277 base::TimeDelta cookie_load_duration_
;
279 // The total number of cookies read. Incremented and reported on the
280 // background runner.
281 int num_cookies_read_
;
283 scoped_refptr
<base::SequencedTaskRunner
> client_task_runner_
;
284 scoped_refptr
<base::SequencedTaskRunner
> background_task_runner_
;
286 // Guards the following metrics-related properties (only accessed when
287 // starting/completing priority loads or completing the total load).
288 base::Lock metrics_lock_
;
289 int num_priority_waiting_
;
290 // The total number of priority requests.
291 int total_priority_requests_
;
292 // The time when |num_priority_waiting_| incremented to 1.
293 base::Time current_priority_wait_start_
;
294 // The cumulative duration of time when |num_priority_waiting_| was greater
296 base::TimeDelta priority_wait_duration_
;
297 // Class with functions that do cryptographic operations (for protecting
298 // cookies stored persistently).
301 CookieCryptoDelegate
* crypto_
;
303 DISALLOW_COPY_AND_ASSIGN(Backend
);
308 // Version number of the database.
310 // Version 8 adds "first-party only" cookies.
312 // Version 7 adds encrypted values. Old values will continue to be used but
313 // all new values written will be encrypted on selected operating systems. New
314 // records read by old clients will simply get an empty cookie value while old
315 // records read by new clients will continue to operate with the unencrypted
316 // version. New and old clients alike will always write/update records with
317 // what they support.
319 // Version 6 adds cookie priorities. This allows developers to influence the
320 // order in which cookies are evicted in order to meet domain cookie limits.
322 // Version 5 adds the columns has_expires and is_persistent, so that the
323 // database can store session cookies as well as persistent cookies. Databases
324 // of version 5 are incompatible with older versions of code. If a database of
325 // version 5 is read by older code, session cookies will be treated as normal
326 // cookies. Currently, these fields are written, but not read anymore.
328 // In version 4, we migrated the time epoch. If you open the DB with an older
329 // version on Mac or Linux, the times will look wonky, but the file will likely
330 // be usable. On Windows version 3 and 4 are the same.
332 // Version 3 updated the database to include the last access time, so we can
333 // expire them in decreasing order of use when we've reached the maximum
334 // number of cookies.
335 const int kCurrentVersionNumber
= 8;
336 const int kCompatibleVersionNumber
= 5;
338 // Possible values for the 'priority' column.
339 enum DBCookiePriority
{
340 kCookiePriorityLow
= 0,
341 kCookiePriorityMedium
= 1,
342 kCookiePriorityHigh
= 2,
345 DBCookiePriority
CookiePriorityToDBCookiePriority(net::CookiePriority value
) {
347 case net::COOKIE_PRIORITY_LOW
:
348 return kCookiePriorityLow
;
349 case net::COOKIE_PRIORITY_MEDIUM
:
350 return kCookiePriorityMedium
;
351 case net::COOKIE_PRIORITY_HIGH
:
352 return kCookiePriorityHigh
;
356 return kCookiePriorityMedium
;
359 net::CookiePriority
DBCookiePriorityToCookiePriority(DBCookiePriority value
) {
361 case kCookiePriorityLow
:
362 return net::COOKIE_PRIORITY_LOW
;
363 case kCookiePriorityMedium
:
364 return net::COOKIE_PRIORITY_MEDIUM
;
365 case kCookiePriorityHigh
:
366 return net::COOKIE_PRIORITY_HIGH
;
370 return net::COOKIE_PRIORITY_DEFAULT
;
373 // Increments a specified TimeDelta by the duration between this object's
374 // constructor and destructor. Not thread safe. Multiple instances may be
375 // created with the same delta instance as long as their lifetimes are nested.
376 // The shortest lived instances have no impact.
377 class IncrementTimeDelta
{
379 explicit IncrementTimeDelta(base::TimeDelta
* delta
) :
381 original_value_(*delta
),
382 start_(base::Time::Now()) {}
384 ~IncrementTimeDelta() {
385 *delta_
= original_value_
+ base::Time::Now() - start_
;
389 base::TimeDelta
* delta_
;
390 base::TimeDelta original_value_
;
393 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta
);
396 // Initializes the cookies table, returning true on success.
397 bool InitTable(sql::Connection
* db
) {
398 if (!db
->DoesTableExist("cookies")) {
399 std::string
stmt(base::StringPrintf(
400 "CREATE TABLE cookies ("
401 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
402 "host_key TEXT NOT NULL,"
403 "name TEXT NOT NULL,"
404 "value TEXT NOT NULL,"
405 "path TEXT NOT NULL,"
406 "expires_utc INTEGER NOT NULL,"
407 "secure INTEGER NOT NULL,"
408 "httponly INTEGER NOT NULL,"
409 "last_access_utc INTEGER NOT NULL, "
410 "has_expires INTEGER NOT NULL DEFAULT 1, "
411 "persistent INTEGER NOT NULL DEFAULT 1,"
412 "priority INTEGER NOT NULL DEFAULT %d,"
413 "encrypted_value BLOB DEFAULT '',"
414 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
415 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT
)));
416 if (!db
->Execute(stmt
.c_str()))
420 // Older code created an index on creation_utc, which is already
421 // primary key for the table.
422 if (!db
->Execute("DROP INDEX IF EXISTS cookie_times"))
425 if (!db
->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
433 void SQLitePersistentCookieStore::Backend::Load(
434 const LoadedCallback
& loaded_callback
) {
435 // This function should be called only once per instance.
437 PostBackgroundTask(FROM_HERE
, base::Bind(
438 &Backend::LoadAndNotifyInBackground
, this,
439 loaded_callback
, base::Time::Now()));
442 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
443 const std::string
& key
,
444 const LoadedCallback
& loaded_callback
) {
446 base::AutoLock
locked(metrics_lock_
);
447 if (num_priority_waiting_
== 0)
448 current_priority_wait_start_
= base::Time::Now();
449 num_priority_waiting_
++;
450 total_priority_requests_
++;
453 PostBackgroundTask(FROM_HERE
, base::Bind(
454 &Backend::LoadKeyAndNotifyInBackground
,
455 this, key
, loaded_callback
, base::Time::Now()));
458 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
459 const LoadedCallback
& loaded_callback
, const base::Time
& posted_at
) {
460 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
461 IncrementTimeDelta
increment(&cookie_load_duration_
);
463 UMA_HISTOGRAM_CUSTOM_TIMES(
464 "Cookie.TimeLoadDBQueueWait",
465 base::Time::Now() - posted_at
,
466 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
469 if (!InitializeDatabase()) {
470 PostClientTask(FROM_HERE
, base::Bind(
471 &Backend::CompleteLoadInForeground
, this, loaded_callback
, false));
473 ChainLoadCookies(loaded_callback
);
477 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
478 const std::string
& key
,
479 const LoadedCallback
& loaded_callback
,
480 const base::Time
& posted_at
) {
481 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
482 IncrementTimeDelta
increment(&cookie_load_duration_
);
484 UMA_HISTOGRAM_CUSTOM_TIMES(
485 "Cookie.TimeKeyLoadDBQueueWait",
486 base::Time::Now() - posted_at
,
487 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
490 bool success
= false;
491 if (InitializeDatabase()) {
492 std::map
<std::string
, std::set
<std::string
> >::iterator
493 it
= keys_to_load_
.find(key
);
494 if (it
!= keys_to_load_
.end()) {
495 success
= LoadCookiesForDomains(it
->second
);
496 keys_to_load_
.erase(it
);
502 PostClientTask(FROM_HERE
, base::Bind(
503 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground
,
504 this, loaded_callback
, success
));
507 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
508 const LoadedCallback
& loaded_callback
,
510 DCHECK(client_task_runner_
->RunsTasksOnCurrentThread());
512 Notify(loaded_callback
, load_success
);
515 base::AutoLock
locked(metrics_lock_
);
516 num_priority_waiting_
--;
517 if (num_priority_waiting_
== 0) {
518 priority_wait_duration_
+=
519 base::Time::Now() - current_priority_wait_start_
;
525 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
526 UMA_HISTOGRAM_CUSTOM_TIMES(
528 cookie_load_duration_
,
529 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
533 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
534 PostBackgroundTask(FROM_HERE
, base::Bind(
535 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground
, this));
538 base::AutoLock
locked(metrics_lock_
);
539 UMA_HISTOGRAM_CUSTOM_TIMES(
540 "Cookie.PriorityBlockingTime",
541 priority_wait_duration_
,
542 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
545 UMA_HISTOGRAM_COUNTS_100(
546 "Cookie.PriorityLoadCount",
547 total_priority_requests_
);
549 UMA_HISTOGRAM_COUNTS_10000(
550 "Cookie.NumberOfLoadedCookies",
555 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
556 const LoadedCallback
& loaded_callback
, bool load_success
) {
557 Notify(loaded_callback
, load_success
);
563 void SQLitePersistentCookieStore::Backend::Notify(
564 const LoadedCallback
& loaded_callback
,
566 DCHECK(client_task_runner_
->RunsTasksOnCurrentThread());
568 std::vector
<net::CanonicalCookie
*> cookies
;
570 base::AutoLock
locked(lock_
);
571 cookies
.swap(cookies_
);
574 loaded_callback
.Run(cookies
);
577 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
578 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
580 if (initialized_
|| corruption_detected_
) {
581 // Return false if we were previously initialized but the DB has since been
582 // closed, or if corruption caused a database reset during initialization.
586 base::Time start
= base::Time::Now();
588 const base::FilePath dir
= path_
.DirName();
589 if (!base::PathExists(dir
) && !base::CreateDirectory(dir
)) {
594 if (base::GetFileSize(path_
, &db_size
))
595 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size
/ 1024 );
597 db_
.reset(new sql::Connection
);
598 db_
->set_histogram_tag("Cookie");
600 // Unretained to avoid a ref loop with |db_|.
601 db_
->set_error_callback(
602 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback
,
603 base::Unretained(this)));
605 if (!db_
->Open(path_
)) {
606 NOTREACHED() << "Unable to open cookie DB.";
607 if (corruption_detected_
)
614 if (!EnsureDatabaseVersion() || !InitTable(db_
.get())) {
615 NOTREACHED() << "Unable to open cookie DB.";
616 if (corruption_detected_
)
623 UMA_HISTOGRAM_CUSTOM_TIMES(
624 "Cookie.TimeInitializeDB",
625 base::Time::Now() - start
,
626 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
629 start
= base::Time::Now();
631 // Retrieve all the domains
632 sql::Statement
smt(db_
->GetUniqueStatement(
633 "SELECT DISTINCT host_key FROM cookies"));
635 if (!smt
.is_valid()) {
636 if (corruption_detected_
)
643 std::vector
<std::string
> host_keys
;
645 host_keys
.push_back(smt
.ColumnString(0));
647 UMA_HISTOGRAM_CUSTOM_TIMES(
648 "Cookie.TimeLoadDomains",
649 base::Time::Now() - start
,
650 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
653 base::Time start_parse
= base::Time::Now();
655 // Build a map of domain keys (always eTLD+1) to domains.
656 for (size_t idx
= 0; idx
< host_keys
.size(); ++idx
) {
657 const std::string
& domain
= host_keys
[idx
];
659 net::registry_controlled_domains::GetDomainAndRegistry(
661 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
663 keys_to_load_
[key
].insert(domain
);
666 UMA_HISTOGRAM_CUSTOM_TIMES(
667 "Cookie.TimeParseDomains",
668 base::Time::Now() - start_parse
,
669 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
672 UMA_HISTOGRAM_CUSTOM_TIMES(
673 "Cookie.TimeInitializeDomainMap",
674 base::Time::Now() - start
,
675 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
682 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
683 const LoadedCallback
& loaded_callback
) {
684 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
685 IncrementTimeDelta
increment(&cookie_load_duration_
);
687 bool load_success
= true;
690 // Close() has been called on this store.
691 load_success
= false;
692 } else if (keys_to_load_
.size() > 0) {
693 // Load cookies for the first domain key.
694 std::map
<std::string
, std::set
<std::string
> >::iterator
695 it
= keys_to_load_
.begin();
696 load_success
= LoadCookiesForDomains(it
->second
);
697 keys_to_load_
.erase(it
);
700 // If load is successful and there are more domain keys to be loaded,
701 // then post a background task to continue chain-load;
702 // Otherwise notify on client runner.
703 if (load_success
&& keys_to_load_
.size() > 0) {
704 bool success
= background_task_runner_
->PostDelayedTask(
706 base::Bind(&Backend::ChainLoadCookies
, this, loaded_callback
),
707 base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds
));
709 LOG(WARNING
) << "Failed to post task from " << FROM_HERE
.ToString()
710 << " to background_task_runner_.";
713 FinishedLoadingCookies(loaded_callback
, load_success
);
717 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
718 const std::set
<std::string
>& domains
) {
719 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
722 if (restore_old_session_cookies_
) {
723 smt
.Assign(db_
->GetCachedStatement(
725 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
726 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
727 "has_expires, persistent, priority FROM cookies WHERE host_key = ?"));
729 smt
.Assign(db_
->GetCachedStatement(
731 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
732 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
733 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
734 "AND persistent = 1"));
736 if (!smt
.is_valid()) {
737 smt
.Clear(); // Disconnect smt_ref from db_.
743 std::vector
<net::CanonicalCookie
*> cookies
;
744 std::set
<std::string
>::const_iterator it
= domains
.begin();
745 for (; it
!= domains
.end(); ++it
) {
746 smt
.BindString(0, *it
);
747 MakeCookiesFromSQLStatement(&cookies
, &smt
);
751 base::AutoLock
locked(lock_
);
752 cookies_
.insert(cookies_
.end(), cookies
.begin(), cookies
.end());
757 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
758 std::vector
<net::CanonicalCookie
*>* cookies
,
759 sql::Statement
* statement
) {
760 sql::Statement
& smt
= *statement
;
763 std::string encrypted_value
= smt
.ColumnString(4);
764 if (!encrypted_value
.empty() && crypto_
) {
765 crypto_
->DecryptString(encrypted_value
, &value
);
767 DCHECK(encrypted_value
.empty());
768 value
= smt
.ColumnString(3);
770 scoped_ptr
<net::CanonicalCookie
> cc(new net::CanonicalCookie(
771 // The "source" URL is not used with persisted cookies.
773 smt
.ColumnString(2), // name
775 smt
.ColumnString(1), // domain
776 smt
.ColumnString(5), // path
777 Time::FromInternalValue(smt
.ColumnInt64(0)), // creation_utc
778 Time::FromInternalValue(smt
.ColumnInt64(6)), // expires_utc
779 Time::FromInternalValue(smt
.ColumnInt64(10)), // last_access_utc
780 smt
.ColumnInt(7) != 0, // secure
781 smt
.ColumnInt(8) != 0, // httponly
782 smt
.ColumnInt(9) != 0, // firstpartyonly
783 DBCookiePriorityToCookiePriority(
784 static_cast<DBCookiePriority
>(smt
.ColumnInt(13))))); // priority
785 DLOG_IF(WARNING
, cc
->CreationDate() > Time::Now())
786 << L
"CreationDate too recent";
787 cookies_per_origin_
[CookieOrigin(cc
->Domain(), cc
->IsSecure())]++;
788 cookies
->push_back(cc
.release());
793 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
795 if (!meta_table_
.Init(
796 db_
.get(), kCurrentVersionNumber
, kCompatibleVersionNumber
)) {
800 if (meta_table_
.GetCompatibleVersionNumber() > kCurrentVersionNumber
) {
801 LOG(WARNING
) << "Cookie database is too new.";
805 int cur_version
= meta_table_
.GetVersionNumber();
806 if (cur_version
== 2) {
807 sql::Transaction
transaction(db_
.get());
808 if (!transaction
.Begin())
810 if (!db_
->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
811 "INTEGER DEFAULT 0") ||
812 !db_
->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
813 LOG(WARNING
) << "Unable to update cookie database to version 3.";
817 meta_table_
.SetVersionNumber(cur_version
);
818 meta_table_
.SetCompatibleVersionNumber(
819 std::min(cur_version
, kCompatibleVersionNumber
));
820 transaction
.Commit();
823 if (cur_version
== 3) {
824 // The time epoch changed for Mac & Linux in this version to match Windows.
825 // This patch came after the main epoch change happened, so some
826 // developers have "good" times for cookies added by the more recent
827 // versions. So we have to be careful to only update times that are under
828 // the old system (which will appear to be from before 1970 in the new
829 // system). The magic number used below is 1970 in our time units.
830 sql::Transaction
transaction(db_
.get());
833 ignore_result(db_
->Execute(
835 "SET creation_utc = creation_utc + 11644473600000000 "
837 "(SELECT rowid FROM cookies WHERE "
838 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
839 ignore_result(db_
->Execute(
841 "SET expires_utc = expires_utc + 11644473600000000 "
843 "(SELECT rowid FROM cookies WHERE "
844 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
845 ignore_result(db_
->Execute(
847 "SET last_access_utc = last_access_utc + 11644473600000000 "
849 "(SELECT rowid FROM cookies WHERE "
850 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
853 meta_table_
.SetVersionNumber(cur_version
);
854 transaction
.Commit();
857 if (cur_version
== 4) {
858 const base::TimeTicks start_time
= base::TimeTicks::Now();
859 sql::Transaction
transaction(db_
.get());
860 if (!transaction
.Begin())
862 if (!db_
->Execute("ALTER TABLE cookies "
863 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
864 !db_
->Execute("ALTER TABLE cookies "
865 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
866 LOG(WARNING
) << "Unable to update cookie database to version 5.";
870 meta_table_
.SetVersionNumber(cur_version
);
871 meta_table_
.SetCompatibleVersionNumber(
872 std::min(cur_version
, kCompatibleVersionNumber
));
873 transaction
.Commit();
874 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
875 base::TimeTicks::Now() - start_time
);
878 if (cur_version
== 5) {
879 const base::TimeTicks start_time
= base::TimeTicks::Now();
880 sql::Transaction
transaction(db_
.get());
881 if (!transaction
.Begin())
883 // Alter the table to add the priority column with a default value.
884 std::string
stmt(base::StringPrintf(
885 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
886 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT
)));
887 if (!db_
->Execute(stmt
.c_str())) {
888 LOG(WARNING
) << "Unable to update cookie database to version 6.";
892 meta_table_
.SetVersionNumber(cur_version
);
893 meta_table_
.SetCompatibleVersionNumber(
894 std::min(cur_version
, kCompatibleVersionNumber
));
895 transaction
.Commit();
896 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
897 base::TimeTicks::Now() - start_time
);
900 if (cur_version
== 6) {
901 const base::TimeTicks start_time
= base::TimeTicks::Now();
902 sql::Transaction
transaction(db_
.get());
903 if (!transaction
.Begin())
905 // Alter the table to add empty "encrypted value" column.
906 if (!db_
->Execute("ALTER TABLE cookies "
907 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
908 LOG(WARNING
) << "Unable to update cookie database to version 7.";
912 meta_table_
.SetVersionNumber(cur_version
);
913 meta_table_
.SetCompatibleVersionNumber(
914 std::min(cur_version
, kCompatibleVersionNumber
));
915 transaction
.Commit();
916 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
917 base::TimeTicks::Now() - start_time
);
920 if (cur_version
== 7) {
921 const base::TimeTicks start_time
= base::TimeTicks::Now();
922 sql::Transaction
transaction(db_
.get());
923 if (!transaction
.Begin())
925 // Alter the table to add a 'firstpartyonly' column.
927 "ALTER TABLE cookies "
928 "ADD COLUMN firstpartyonly INTEGER DEFAULT 0")) {
929 LOG(WARNING
) << "Unable to update cookie database to version 8.";
933 meta_table_
.SetVersionNumber(cur_version
);
934 meta_table_
.SetCompatibleVersionNumber(
935 std::min(cur_version
, kCompatibleVersionNumber
));
936 transaction
.Commit();
937 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV8",
938 base::TimeTicks::Now() - start_time
);
941 // Put future migration cases here.
943 if (cur_version
< kCurrentVersionNumber
) {
944 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
947 db_
.reset(new sql::Connection
);
948 if (!base::DeleteFile(path_
, false) ||
951 db_
.get(), kCurrentVersionNumber
, kCompatibleVersionNumber
)) {
952 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
953 NOTREACHED() << "Unable to reset the cookie DB.";
963 void SQLitePersistentCookieStore::Backend::AddCookie(
964 const net::CanonicalCookie
& cc
) {
965 BatchOperation(PendingOperation::COOKIE_ADD
, cc
);
968 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
969 const net::CanonicalCookie
& cc
) {
970 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS
, cc
);
973 void SQLitePersistentCookieStore::Backend::DeleteCookie(
974 const net::CanonicalCookie
& cc
) {
975 BatchOperation(PendingOperation::COOKIE_DELETE
, cc
);
978 void SQLitePersistentCookieStore::Backend::BatchOperation(
979 PendingOperation::OperationType op
,
980 const net::CanonicalCookie
& cc
) {
981 // Commit every 30 seconds.
982 static const int kCommitIntervalMs
= 30 * 1000;
983 // Commit right away if we have more than 512 outstanding operations.
984 static const size_t kCommitAfterBatchSize
= 512;
985 DCHECK(!background_task_runner_
->RunsTasksOnCurrentThread());
987 // We do a full copy of the cookie here, and hopefully just here.
988 scoped_ptr
<PendingOperation
> po(new PendingOperation(op
, cc
));
990 PendingOperationsList::size_type num_pending
;
992 base::AutoLock
locked(lock_
);
993 pending_
.push_back(po
.release());
994 num_pending
= ++num_pending_
;
997 if (num_pending
== 1) {
998 // We've gotten our first entry for this batch, fire off the timer.
999 if (!background_task_runner_
->PostDelayedTask(
1000 FROM_HERE
, base::Bind(&Backend::Commit
, this),
1001 base::TimeDelta::FromMilliseconds(kCommitIntervalMs
))) {
1002 NOTREACHED() << "background_task_runner_ is not running.";
1004 } else if (num_pending
== kCommitAfterBatchSize
) {
1005 // We've reached a big enough batch, fire off a commit now.
1006 PostBackgroundTask(FROM_HERE
, base::Bind(&Backend::Commit
, this));
1010 void SQLitePersistentCookieStore::Backend::Commit() {
1011 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1013 PendingOperationsList ops
;
1015 base::AutoLock
locked(lock_
);
1020 // Maybe an old timer fired or we are already Close()'ed.
1021 if (!db_
.get() || ops
.empty())
1024 sql::Statement
add_smt(db_
->GetCachedStatement(
1026 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1027 "encrypted_value, path, expires_utc, secure, httponly, firstpartyonly, "
1028 "last_access_utc, has_expires, persistent, priority) "
1029 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1030 if (!add_smt
.is_valid())
1033 sql::Statement
update_access_smt(db_
->GetCachedStatement(SQL_FROM_HERE
,
1034 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1035 if (!update_access_smt
.is_valid())
1038 sql::Statement
del_smt(db_
->GetCachedStatement(SQL_FROM_HERE
,
1039 "DELETE FROM cookies WHERE creation_utc=?"));
1040 if (!del_smt
.is_valid())
1043 sql::Transaction
transaction(db_
.get());
1044 if (!transaction
.Begin())
1047 for (PendingOperationsList::iterator it
= ops
.begin();
1048 it
!= ops
.end(); ++it
) {
1049 // Free the cookies as we commit them to the database.
1050 scoped_ptr
<PendingOperation
> po(*it
);
1052 case PendingOperation::COOKIE_ADD
:
1053 cookies_per_origin_
[
1054 CookieOrigin(po
->cc().Domain(), po
->cc().IsSecure())]++;
1055 add_smt
.Reset(true);
1056 add_smt
.BindInt64(0, po
->cc().CreationDate().ToInternalValue());
1057 add_smt
.BindString(1, po
->cc().Domain());
1058 add_smt
.BindString(2, po
->cc().Name());
1060 std::string encrypted_value
;
1061 add_smt
.BindCString(3, ""); // value
1062 crypto_
->EncryptString(po
->cc().Value(), &encrypted_value
);
1063 // BindBlob() immediately makes an internal copy of the data.
1064 add_smt
.BindBlob(4, encrypted_value
.data(),
1065 static_cast<int>(encrypted_value
.length()));
1067 add_smt
.BindString(3, po
->cc().Value());
1068 add_smt
.BindBlob(4, "", 0); // encrypted_value
1070 add_smt
.BindString(5, po
->cc().Path());
1071 add_smt
.BindInt64(6, po
->cc().ExpiryDate().ToInternalValue());
1072 add_smt
.BindInt(7, po
->cc().IsSecure());
1073 add_smt
.BindInt(8, po
->cc().IsHttpOnly());
1074 add_smt
.BindInt(9, po
->cc().IsFirstPartyOnly());
1075 add_smt
.BindInt64(10, po
->cc().LastAccessDate().ToInternalValue());
1076 add_smt
.BindInt(11, po
->cc().IsPersistent());
1077 add_smt
.BindInt(12, po
->cc().IsPersistent());
1079 CookiePriorityToDBCookiePriority(po
->cc().Priority()));
1081 NOTREACHED() << "Could not add a cookie to the DB.";
1084 case PendingOperation::COOKIE_UPDATEACCESS
:
1085 update_access_smt
.Reset(true);
1086 update_access_smt
.BindInt64(0,
1087 po
->cc().LastAccessDate().ToInternalValue());
1088 update_access_smt
.BindInt64(1,
1089 po
->cc().CreationDate().ToInternalValue());
1090 if (!update_access_smt
.Run())
1091 NOTREACHED() << "Could not update cookie last access time in the DB.";
1094 case PendingOperation::COOKIE_DELETE
:
1095 cookies_per_origin_
[
1096 CookieOrigin(po
->cc().Domain(), po
->cc().IsSecure())]--;
1097 del_smt
.Reset(true);
1098 del_smt
.BindInt64(0, po
->cc().CreationDate().ToInternalValue());
1100 NOTREACHED() << "Could not delete a cookie from the DB.";
1108 bool succeeded
= transaction
.Commit();
1109 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1110 succeeded
? 0 : 1, 2);
1113 void SQLitePersistentCookieStore::Backend::Flush(
1114 const base::Closure
& callback
) {
1115 DCHECK(!background_task_runner_
->RunsTasksOnCurrentThread());
1116 PostBackgroundTask(FROM_HERE
, base::Bind(&Backend::Commit
, this));
1118 if (!callback
.is_null()) {
1119 // We want the completion task to run immediately after Commit() returns.
1120 // Posting it from here means there is less chance of another task getting
1121 // onto the message queue first, than if we posted it from Commit() itself.
1122 PostBackgroundTask(FROM_HERE
, callback
);
1126 // Fire off a close message to the background runner. We could still have a
1127 // pending commit timer or Load operations holding references on us, but if/when
1128 // this fires we will already have been cleaned up and it will be ignored.
1129 void SQLitePersistentCookieStore::Backend::Close() {
1130 if (background_task_runner_
->RunsTasksOnCurrentThread()) {
1131 InternalBackgroundClose();
1133 // Must close the backend on the background runner.
1134 PostBackgroundTask(FROM_HERE
,
1135 base::Bind(&Backend::InternalBackgroundClose
, this));
1139 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1140 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1141 // Commit any pending operations
1144 if (!force_keep_session_state_
&& special_storage_policy_
.get() &&
1145 special_storage_policy_
->HasSessionOnlyOrigins()) {
1146 DeleteSessionCookiesOnShutdown();
1149 meta_table_
.Reset();
1153 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1154 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1159 if (!special_storage_policy_
.get())
1162 sql::Statement
del_smt(db_
->GetCachedStatement(
1163 SQL_FROM_HERE
, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1164 if (!del_smt
.is_valid()) {
1165 LOG(WARNING
) << "Unable to delete cookies on shutdown.";
1169 sql::Transaction
transaction(db_
.get());
1170 if (!transaction
.Begin()) {
1171 LOG(WARNING
) << "Unable to delete cookies on shutdown.";
1175 for (CookiesPerOriginMap::iterator it
= cookies_per_origin_
.begin();
1176 it
!= cookies_per_origin_
.end(); ++it
) {
1177 if (it
->second
<= 0) {
1178 DCHECK_EQ(0, it
->second
);
1181 const GURL
url(net::cookie_util::CookieOriginToURL(it
->first
.first
,
1183 if (!url
.is_valid() || !special_storage_policy_
->IsStorageSessionOnly(url
))
1186 del_smt
.Reset(true);
1187 del_smt
.BindString(0, it
->first
.first
);
1188 del_smt
.BindInt(1, it
->first
.second
);
1190 NOTREACHED() << "Could not delete a cookie from the DB.";
1193 if (!transaction
.Commit())
1194 LOG(WARNING
) << "Unable to delete cookies on shutdown.";
1197 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1199 sql::Statement
* stmt
) {
1200 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1202 if (!sql::IsErrorCatastrophic(error
))
1205 // TODO(shess): Running KillDatabase() multiple times should be
1207 if (corruption_detected_
)
1210 corruption_detected_
= true;
1212 // Don't just do the close/delete here, as we are being called by |db| and
1213 // that seems dangerous.
1214 // TODO(shess): Consider just calling RazeAndClose() immediately.
1215 // db_ may not be safe to reset at this point, but RazeAndClose()
1216 // would cause the stack to unwind safely with errors.
1217 PostBackgroundTask(FROM_HERE
, base::Bind(&Backend::KillDatabase
, this));
1220 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1221 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1224 // This Backend will now be in-memory only. In a future run we will recreate
1225 // the database. Hopefully things go better then!
1226 bool success
= db_
->RazeAndClose();
1227 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success
);
1228 meta_table_
.Reset();
1233 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1234 base::AutoLock
locked(lock_
);
1235 force_keep_session_state_
= true;
1238 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1239 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1240 if (!db_
->Execute("DELETE FROM cookies WHERE persistent == 0"))
1241 LOG(WARNING
) << "Unable to delete session cookies.";
1244 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1245 const tracked_objects::Location
& origin
, const base::Closure
& task
) {
1246 if (!background_task_runner_
->PostTask(origin
, task
)) {
1247 LOG(WARNING
) << "Failed to post task from " << origin
.ToString()
1248 << " to background_task_runner_.";
1252 void SQLitePersistentCookieStore::Backend::PostClientTask(
1253 const tracked_objects::Location
& origin
, const base::Closure
& task
) {
1254 if (!client_task_runner_
->PostTask(origin
, task
)) {
1255 LOG(WARNING
) << "Failed to post task from " << origin
.ToString()
1256 << " to client_task_runner_.";
1260 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1261 const LoadedCallback
& loaded_callback
,
1263 PostClientTask(FROM_HERE
, base::Bind(&Backend::CompleteLoadInForeground
, this,
1264 loaded_callback
, success
));
1265 if (success
&& !restore_old_session_cookies_
)
1266 DeleteSessionCookiesOnStartup();
1269 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1270 const base::FilePath
& path
,
1271 const scoped_refptr
<base::SequencedTaskRunner
>& client_task_runner
,
1272 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
,
1273 bool restore_old_session_cookies
,
1274 storage::SpecialStoragePolicy
* special_storage_policy
,
1275 CookieCryptoDelegate
* crypto_delegate
)
1276 : backend_(new Backend(path
,
1278 background_task_runner
,
1279 restore_old_session_cookies
,
1280 special_storage_policy
,
1284 void SQLitePersistentCookieStore::Load(const LoadedCallback
& loaded_callback
) {
1285 backend_
->Load(loaded_callback
);
1288 void SQLitePersistentCookieStore::LoadCookiesForKey(
1289 const std::string
& key
,
1290 const LoadedCallback
& loaded_callback
) {
1291 backend_
->LoadCookiesForKey(key
, loaded_callback
);
1294 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie
& cc
) {
1295 backend_
->AddCookie(cc
);
1298 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1299 const net::CanonicalCookie
& cc
) {
1300 backend_
->UpdateCookieAccessTime(cc
);
1303 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie
& cc
) {
1304 backend_
->DeleteCookie(cc
);
1307 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1308 backend_
->SetForceKeepSessionState();
1311 void SQLitePersistentCookieStore::Flush(const base::Closure
& callback
) {
1312 backend_
->Flush(callback
);
1315 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1317 // We release our reference to the Backend, though it will probably still have
1318 // a reference if the background runner has not run Close() yet.
1321 CookieStoreConfig::CookieStoreConfig()
1322 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES
),
1323 crypto_delegate(NULL
) {
1324 // Default to an in-memory cookie store.
1327 CookieStoreConfig::CookieStoreConfig(
1328 const base::FilePath
& path
,
1329 SessionCookieMode session_cookie_mode
,
1330 storage::SpecialStoragePolicy
* storage_policy
,
1331 net::CookieMonsterDelegate
* cookie_delegate
)
1333 session_cookie_mode(session_cookie_mode
),
1334 storage_policy(storage_policy
),
1335 cookie_delegate(cookie_delegate
),
1336 crypto_delegate(NULL
) {
1337 CHECK(!path
.empty() || session_cookie_mode
== EPHEMERAL_SESSION_COOKIES
);
1340 CookieStoreConfig::~CookieStoreConfig() {
1343 net::CookieStore
* CreateCookieStore(const CookieStoreConfig
& config
) {
1344 net::CookieMonster
* cookie_monster
= NULL
;
1346 if (config
.path
.empty()) {
1347 // Empty path means in-memory store.
1348 cookie_monster
= new net::CookieMonster(NULL
, config
.cookie_delegate
.get());
1350 scoped_refptr
<base::SequencedTaskRunner
> client_task_runner
=
1351 config
.client_task_runner
;
1352 scoped_refptr
<base::SequencedTaskRunner
> background_task_runner
=
1353 config
.background_task_runner
;
1355 if (!client_task_runner
.get()) {
1356 client_task_runner
=
1357 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
1360 if (!background_task_runner
.get()) {
1361 background_task_runner
=
1362 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1363 BrowserThread::GetBlockingPool()->GetSequenceToken());
1366 SQLitePersistentCookieStore
* persistent_store
=
1367 new SQLitePersistentCookieStore(
1370 background_task_runner
,
1371 (config
.session_cookie_mode
==
1372 CookieStoreConfig::RESTORED_SESSION_COOKIES
),
1373 config
.storage_policy
.get(),
1374 config
.crypto_delegate
);
1377 new net::CookieMonster(persistent_store
, config
.cookie_delegate
.get());
1378 if ((config
.session_cookie_mode
==
1379 CookieStoreConfig::PERSISTANT_SESSION_COOKIES
) ||
1380 (config
.session_cookie_mode
==
1381 CookieStoreConfig::RESTORED_SESSION_COOKIES
)) {
1382 cookie_monster
->SetPersistSessionCookies(true);
1386 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1387 switches::kEnableFileCookies
)) {
1388 cookie_monster
->SetEnableFileScheme(true);
1391 return cookie_monster
;
1394 } // namespace content