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/file_util.h"
16 #include "base/files/file_path.h"
17 #include "base/location.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/metrics/field_trial.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_store_factory.h"
31 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
32 #include "net/cookies/canonical_cookie.h"
33 #include "net/cookies/cookie_constants.h"
34 #include "net/cookies/cookie_util.h"
35 #include "sql/error_delegate_util.h"
36 #include "sql/meta_table.h"
37 #include "sql/statement.h"
38 #include "sql/transaction.h"
39 #include "third_party/sqlite/sqlite3.h"
41 #include "webkit/browser/quota/special_storage_policy.h"
47 // This class is designed to be shared between any client thread and the
48 // background task runner. It batches operations and commits them on a timer.
50 // SQLitePersistentCookieStore::Load is called to load all cookies. It
51 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
52 // task to the background runner. This task calls Backend::ChainLoadCookies(),
53 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
54 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
55 // posted to the client runner, which notifies the caller of
56 // SQLitePersistentCookieStore::Load that the load is complete.
58 // If a priority load request is invoked via SQLitePersistentCookieStore::
59 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
60 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
61 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
62 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
63 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
65 // Subsequent to loading, mutations may be queued by any thread using
66 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
67 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
68 // whichever occurs first.
69 class SQLitePersistentCookieStore::Backend
70 : public base::RefCountedThreadSafe
<SQLitePersistentCookieStore::Backend
> {
73 const base::FilePath
& path
,
74 const scoped_refptr
<base::SequencedTaskRunner
>& client_task_runner
,
75 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
,
76 bool restore_old_session_cookies
,
77 quota::SpecialStoragePolicy
* special_storage_policy
)
80 force_keep_session_state_(false),
82 corruption_detected_(false),
83 restore_old_session_cookies_(restore_old_session_cookies
),
84 special_storage_policy_(special_storage_policy
),
86 client_task_runner_(client_task_runner
),
87 background_task_runner_(background_task_runner
),
88 num_priority_waiting_(0),
89 total_priority_requests_(0) {}
91 // Creates or loads the SQLite database.
92 void Load(const LoadedCallback
& loaded_callback
);
94 // Loads cookies for the domain key (eTLD+1).
95 void LoadCookiesForKey(const std::string
& domain
,
96 const LoadedCallback
& loaded_callback
);
98 // Batch a cookie addition.
99 void AddCookie(const net::CanonicalCookie
& cc
);
101 // Batch a cookie access time update.
102 void UpdateCookieAccessTime(const net::CanonicalCookie
& cc
);
104 // Batch a cookie deletion.
105 void DeleteCookie(const net::CanonicalCookie
& cc
);
107 // Commit pending operations as soon as possible.
108 void Flush(const base::Closure
& callback
);
110 // Commit any pending operations and close the database. This must be called
111 // before the object is destructed.
114 void SetForceKeepSessionState();
117 friend class base::RefCountedThreadSafe
<SQLitePersistentCookieStore::Backend
>;
119 // You should call Close() before destructing this object.
121 DCHECK(!db_
.get()) << "Close should have already been called.";
122 DCHECK(num_pending_
== 0 && pending_
.empty());
125 // Database upgrade statements.
126 bool EnsureDatabaseVersion();
128 class PendingOperation
{
136 PendingOperation(OperationType op
, const net::CanonicalCookie
& cc
)
137 : op_(op
), cc_(cc
) { }
139 OperationType
op() const { return op_
; }
140 const net::CanonicalCookie
& cc() const { return cc_
; }
144 net::CanonicalCookie cc_
;
148 // Creates or loads the SQLite database on background runner.
149 void LoadAndNotifyInBackground(const LoadedCallback
& loaded_callback
,
150 const base::Time
& posted_at
);
152 // Loads cookies for the domain key (eTLD+1) on background runner.
153 void LoadKeyAndNotifyInBackground(const std::string
& domains
,
154 const LoadedCallback
& loaded_callback
,
155 const base::Time
& posted_at
);
157 // Notifies the CookieMonster when loading completes for a specific domain key
158 // or for all domain keys. Triggers the callback and passes it all cookies
159 // that have been loaded from DB since last IO notification.
160 void Notify(const LoadedCallback
& loaded_callback
, bool load_success
);
162 // Sends notification when the entire store is loaded, and reports metrics
163 // for the total time to load and aggregated results from any priority loads
165 void CompleteLoadInForeground(const LoadedCallback
& loaded_callback
,
168 // Sends notification when a single priority load completes. Updates priority
169 // load metric data. The data is sent only after the final load completes.
170 void CompleteLoadForKeyInForeground(const LoadedCallback
& loaded_callback
,
173 // Sends all metrics, including posting a ReportMetricsInBackground task.
174 // Called after all priority and regular loading is complete.
175 void ReportMetrics();
177 // Sends background-runner owned metrics (i.e., the combined duration of all
179 void ReportMetricsInBackground();
181 // Initialize the data base.
182 bool InitializeDatabase();
184 // Loads cookies for the next domain key from the DB, then either reschedules
185 // itself or schedules the provided callback to run on the client runner (if
186 // all domains are loaded).
187 void ChainLoadCookies(const LoadedCallback
& loaded_callback
);
189 // Load all cookies for a set of domains/hosts
190 bool LoadCookiesForDomains(const std::set
<std::string
>& key
);
192 // Batch a cookie operation (add or delete)
193 void BatchOperation(PendingOperation::OperationType op
,
194 const net::CanonicalCookie
& cc
);
195 // Commit our pending operations to the database.
197 // Close() executed on the background runner.
198 void InternalBackgroundClose();
200 void DeleteSessionCookiesOnStartup();
202 void DeleteSessionCookiesOnShutdown();
204 void DatabaseErrorCallback(int error
, sql::Statement
* stmt
);
207 void PostBackgroundTask(const tracked_objects::Location
& origin
,
208 const base::Closure
& task
);
209 void PostClientTask(const tracked_objects::Location
& origin
,
210 const base::Closure
& task
);
212 base::FilePath path_
;
213 scoped_ptr
<sql::Connection
> db_
;
214 sql::MetaTable meta_table_
;
216 typedef std::list
<PendingOperation
*> PendingOperationsList
;
217 PendingOperationsList pending_
;
218 PendingOperationsList::size_type num_pending_
;
219 // True if the persistent store should skip delete on exit rules.
220 bool force_keep_session_state_
;
221 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
224 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
225 // the number of messages sent to the client runner. Sent back in response to
226 // individual load requests for domain keys or when all loading completes.
227 std::vector
<net::CanonicalCookie
*> cookies_
;
229 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
230 std::map
<std::string
, std::set
<std::string
> > keys_to_load_
;
232 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
234 typedef std::pair
<std::string
, bool> CookieOrigin
;
235 typedef std::map
<CookieOrigin
, int> CookiesPerOriginMap
;
236 CookiesPerOriginMap cookies_per_origin_
;
238 // Indicates if DB has been initialized.
241 // Indicates if the kill-database callback has been scheduled.
242 bool corruption_detected_
;
244 // If false, we should filter out session cookies when reading the DB.
245 bool restore_old_session_cookies_
;
247 // Policy defining what data is deleted on shutdown.
248 scoped_refptr
<quota::SpecialStoragePolicy
> special_storage_policy_
;
250 // The cumulative time spent loading the cookies on the background runner.
251 // Incremented and reported from the background runner.
252 base::TimeDelta cookie_load_duration_
;
254 // The total number of cookies read. Incremented and reported on the
255 // background runner.
256 int num_cookies_read_
;
258 scoped_refptr
<base::SequencedTaskRunner
> client_task_runner_
;
259 scoped_refptr
<base::SequencedTaskRunner
> background_task_runner_
;
261 // Guards the following metrics-related properties (only accessed when
262 // starting/completing priority loads or completing the total load).
263 base::Lock metrics_lock_
;
264 int num_priority_waiting_
;
265 // The total number of priority requests.
266 int total_priority_requests_
;
267 // The time when |num_priority_waiting_| incremented to 1.
268 base::Time current_priority_wait_start_
;
269 // The cumulative duration of time when |num_priority_waiting_| was greater
271 base::TimeDelta priority_wait_duration_
;
273 DISALLOW_COPY_AND_ASSIGN(Backend
);
278 // Version number of the database.
280 // Version 6 adds cookie priorities. This allows developers to influence the
281 // order in which cookies are evicted in order to meet domain cookie limits.
283 // Version 5 adds the columns has_expires and is_persistent, so that the
284 // database can store session cookies as well as persistent cookies. Databases
285 // of version 5 are incompatible with older versions of code. If a database of
286 // version 5 is read by older code, session cookies will be treated as normal
287 // cookies. Currently, these fields are written, but not read anymore.
289 // In version 4, we migrated the time epoch. If you open the DB with an older
290 // version on Mac or Linux, the times will look wonky, but the file will likely
291 // be usable. On Windows version 3 and 4 are the same.
293 // Version 3 updated the database to include the last access time, so we can
294 // expire them in decreasing order of use when we've reached the maximum
295 // number of cookies.
296 const int kCurrentVersionNumber
= 6;
297 const int kCompatibleVersionNumber
= 5;
299 // Possible values for the 'priority' column.
300 enum DBCookiePriority
{
301 kCookiePriorityLow
= 0,
302 kCookiePriorityMedium
= 1,
303 kCookiePriorityHigh
= 2,
306 DBCookiePriority
CookiePriorityToDBCookiePriority(net::CookiePriority value
) {
308 case net::COOKIE_PRIORITY_LOW
:
309 return kCookiePriorityLow
;
310 case net::COOKIE_PRIORITY_MEDIUM
:
311 return kCookiePriorityMedium
;
312 case net::COOKIE_PRIORITY_HIGH
:
313 return kCookiePriorityHigh
;
317 return kCookiePriorityMedium
;
320 net::CookiePriority
DBCookiePriorityToCookiePriority(DBCookiePriority value
) {
322 case kCookiePriorityLow
:
323 return net::COOKIE_PRIORITY_LOW
;
324 case kCookiePriorityMedium
:
325 return net::COOKIE_PRIORITY_MEDIUM
;
326 case kCookiePriorityHigh
:
327 return net::COOKIE_PRIORITY_HIGH
;
331 return net::COOKIE_PRIORITY_DEFAULT
;
334 // Increments a specified TimeDelta by the duration between this object's
335 // constructor and destructor. Not thread safe. Multiple instances may be
336 // created with the same delta instance as long as their lifetimes are nested.
337 // The shortest lived instances have no impact.
338 class IncrementTimeDelta
{
340 explicit IncrementTimeDelta(base::TimeDelta
* delta
) :
342 original_value_(*delta
),
343 start_(base::Time::Now()) {}
345 ~IncrementTimeDelta() {
346 *delta_
= original_value_
+ base::Time::Now() - start_
;
350 base::TimeDelta
* delta_
;
351 base::TimeDelta original_value_
;
354 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta
);
357 // Initializes the cookies table, returning true on success.
358 bool InitTable(sql::Connection
* db
) {
359 if (!db
->DoesTableExist("cookies")) {
360 std::string
stmt(base::StringPrintf(
361 "CREATE TABLE cookies ("
362 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
363 "host_key TEXT NOT NULL,"
364 "name TEXT NOT NULL,"
365 "value TEXT NOT NULL,"
366 "path TEXT NOT NULL,"
367 "expires_utc INTEGER NOT NULL,"
368 "secure INTEGER NOT NULL,"
369 "httponly INTEGER NOT NULL,"
370 "last_access_utc INTEGER NOT NULL, "
371 "has_expires INTEGER NOT NULL DEFAULT 1, "
372 "persistent INTEGER NOT NULL DEFAULT 1,"
373 "priority INTEGER NOT NULL DEFAULT %d)",
374 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT
)));
375 if (!db
->Execute(stmt
.c_str()))
379 // Older code created an index on creation_utc, which is already
380 // primary key for the table.
381 if (!db
->Execute("DROP INDEX IF EXISTS cookie_times"))
384 if (!db
->Execute("CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)"))
392 void SQLitePersistentCookieStore::Backend::Load(
393 const LoadedCallback
& loaded_callback
) {
394 // This function should be called only once per instance.
396 PostBackgroundTask(FROM_HERE
, base::Bind(
397 &Backend::LoadAndNotifyInBackground
, this,
398 loaded_callback
, base::Time::Now()));
401 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
402 const std::string
& key
,
403 const LoadedCallback
& loaded_callback
) {
405 base::AutoLock
locked(metrics_lock_
);
406 if (num_priority_waiting_
== 0)
407 current_priority_wait_start_
= base::Time::Now();
408 num_priority_waiting_
++;
409 total_priority_requests_
++;
412 PostBackgroundTask(FROM_HERE
, base::Bind(
413 &Backend::LoadKeyAndNotifyInBackground
,
414 this, key
, loaded_callback
, base::Time::Now()));
417 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
418 const LoadedCallback
& loaded_callback
, const base::Time
& posted_at
) {
419 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
420 IncrementTimeDelta
increment(&cookie_load_duration_
);
422 UMA_HISTOGRAM_CUSTOM_TIMES(
423 "Cookie.TimeLoadDBQueueWait",
424 base::Time::Now() - posted_at
,
425 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
428 if (!InitializeDatabase()) {
429 PostClientTask(FROM_HERE
, base::Bind(
430 &Backend::CompleteLoadInForeground
, this, loaded_callback
, false));
432 ChainLoadCookies(loaded_callback
);
436 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
437 const std::string
& key
,
438 const LoadedCallback
& loaded_callback
,
439 const base::Time
& posted_at
) {
440 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
441 IncrementTimeDelta
increment(&cookie_load_duration_
);
443 UMA_HISTOGRAM_CUSTOM_TIMES(
444 "Cookie.TimeKeyLoadDBQueueWait",
445 base::Time::Now() - posted_at
,
446 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
449 bool success
= false;
450 if (InitializeDatabase()) {
451 std::map
<std::string
, std::set
<std::string
> >::iterator
452 it
= keys_to_load_
.find(key
);
453 if (it
!= keys_to_load_
.end()) {
454 success
= LoadCookiesForDomains(it
->second
);
455 keys_to_load_
.erase(it
);
461 PostClientTask(FROM_HERE
, base::Bind(
462 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground
,
463 this, loaded_callback
, success
));
466 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
467 const LoadedCallback
& loaded_callback
,
469 DCHECK(client_task_runner_
->RunsTasksOnCurrentThread());
471 Notify(loaded_callback
, load_success
);
474 base::AutoLock
locked(metrics_lock_
);
475 num_priority_waiting_
--;
476 if (num_priority_waiting_
== 0) {
477 priority_wait_duration_
+=
478 base::Time::Now() - current_priority_wait_start_
;
484 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
485 UMA_HISTOGRAM_CUSTOM_TIMES(
487 cookie_load_duration_
,
488 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
492 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
493 PostBackgroundTask(FROM_HERE
, base::Bind(
494 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground
, this));
497 base::AutoLock
locked(metrics_lock_
);
498 UMA_HISTOGRAM_CUSTOM_TIMES(
499 "Cookie.PriorityBlockingTime",
500 priority_wait_duration_
,
501 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
504 UMA_HISTOGRAM_COUNTS_100(
505 "Cookie.PriorityLoadCount",
506 total_priority_requests_
);
508 UMA_HISTOGRAM_COUNTS_10000(
509 "Cookie.NumberOfLoadedCookies",
514 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
515 const LoadedCallback
& loaded_callback
, bool load_success
) {
516 Notify(loaded_callback
, load_success
);
522 void SQLitePersistentCookieStore::Backend::Notify(
523 const LoadedCallback
& loaded_callback
,
525 DCHECK(client_task_runner_
->RunsTasksOnCurrentThread());
527 std::vector
<net::CanonicalCookie
*> cookies
;
529 base::AutoLock
locked(lock_
);
530 cookies
.swap(cookies_
);
533 loaded_callback
.Run(cookies
);
536 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
537 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
539 if (initialized_
|| corruption_detected_
) {
540 // Return false if we were previously initialized but the DB has since been
541 // closed, or if corruption caused a database reset during initialization.
545 base::Time start
= base::Time::Now();
547 const base::FilePath dir
= path_
.DirName();
548 if (!base::PathExists(dir
) && !file_util::CreateDirectory(dir
)) {
553 if (file_util::GetFileSize(path_
, &db_size
))
554 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size
/ 1024 );
556 db_
.reset(new sql::Connection
);
557 db_
->set_histogram_tag("Cookie");
559 // Unretained to avoid a ref loop with |db_|.
560 db_
->set_error_callback(
561 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback
,
562 base::Unretained(this)));
564 if (!db_
->Open(path_
)) {
565 NOTREACHED() << "Unable to open cookie DB.";
566 if (corruption_detected_
)
573 if (!EnsureDatabaseVersion() || !InitTable(db_
.get())) {
574 NOTREACHED() << "Unable to open cookie DB.";
575 if (corruption_detected_
)
582 UMA_HISTOGRAM_CUSTOM_TIMES(
583 "Cookie.TimeInitializeDB",
584 base::Time::Now() - start
,
585 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
588 start
= base::Time::Now();
590 // Retrieve all the domains
591 sql::Statement
smt(db_
->GetUniqueStatement(
592 "SELECT DISTINCT host_key FROM cookies"));
594 if (!smt
.is_valid()) {
595 if (corruption_detected_
)
602 std::vector
<std::string
> host_keys
;
604 host_keys
.push_back(smt
.ColumnString(0));
606 UMA_HISTOGRAM_CUSTOM_TIMES(
607 "Cookie.TimeLoadDomains",
608 base::Time::Now() - start
,
609 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
612 base::Time start_parse
= base::Time::Now();
614 // Build a map of domain keys (always eTLD+1) to domains.
615 for (size_t idx
= 0; idx
< host_keys
.size(); ++idx
) {
616 const std::string
& domain
= host_keys
[idx
];
618 net::registry_controlled_domains::GetDomainAndRegistry(
620 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
);
622 keys_to_load_
[key
].insert(domain
);
625 UMA_HISTOGRAM_CUSTOM_TIMES(
626 "Cookie.TimeParseDomains",
627 base::Time::Now() - start_parse
,
628 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
631 UMA_HISTOGRAM_CUSTOM_TIMES(
632 "Cookie.TimeInitializeDomainMap",
633 base::Time::Now() - start
,
634 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
641 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
642 const LoadedCallback
& loaded_callback
) {
643 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
644 IncrementTimeDelta
increment(&cookie_load_duration_
);
646 bool load_success
= true;
649 // Close() has been called on this store.
650 load_success
= false;
651 } else if (keys_to_load_
.size() > 0) {
652 // Load cookies for the first domain key.
653 std::map
<std::string
, std::set
<std::string
> >::iterator
654 it
= keys_to_load_
.begin();
655 load_success
= LoadCookiesForDomains(it
->second
);
656 keys_to_load_
.erase(it
);
659 // If load is successful and there are more domain keys to be loaded,
660 // then post a background task to continue chain-load;
661 // Otherwise notify on client runner.
662 if (load_success
&& keys_to_load_
.size() > 0) {
663 PostBackgroundTask(FROM_HERE
, base::Bind(
664 &Backend::ChainLoadCookies
, this, loaded_callback
));
666 PostClientTask(FROM_HERE
, base::Bind(
667 &Backend::CompleteLoadInForeground
, this,
668 loaded_callback
, load_success
));
669 if (load_success
&& !restore_old_session_cookies_
)
670 DeleteSessionCookiesOnStartup();
674 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
675 const std::set
<std::string
>& domains
) {
676 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
679 if (restore_old_session_cookies_
) {
680 smt
.Assign(db_
->GetCachedStatement(
682 "SELECT creation_utc, host_key, name, value, path, expires_utc, "
683 "secure, httponly, last_access_utc, has_expires, persistent, priority "
684 "FROM cookies WHERE host_key = ?"));
686 smt
.Assign(db_
->GetCachedStatement(
688 "SELECT creation_utc, host_key, name, value, path, expires_utc, "
689 "secure, httponly, last_access_utc, has_expires, persistent, priority "
690 "FROM cookies WHERE host_key = ? AND persistent = 1"));
692 if (!smt
.is_valid()) {
693 smt
.Clear(); // Disconnect smt_ref from db_.
699 std::vector
<net::CanonicalCookie
*> cookies
;
700 std::set
<std::string
>::const_iterator it
= domains
.begin();
701 for (; it
!= domains
.end(); ++it
) {
702 smt
.BindString(0, *it
);
704 scoped_ptr
<net::CanonicalCookie
> cc(new net::CanonicalCookie(
705 // The "source" URL is not used with persisted cookies.
707 smt
.ColumnString(2), // name
708 smt
.ColumnString(3), // value
709 smt
.ColumnString(1), // domain
710 smt
.ColumnString(4), // path
711 Time::FromInternalValue(smt
.ColumnInt64(0)), // creation_utc
712 Time::FromInternalValue(smt
.ColumnInt64(5)), // expires_utc
713 Time::FromInternalValue(smt
.ColumnInt64(8)), // last_access_utc
714 smt
.ColumnInt(6) != 0, // secure
715 smt
.ColumnInt(7) != 0, // httponly
716 DBCookiePriorityToCookiePriority(
717 static_cast<DBCookiePriority
>(smt
.ColumnInt(11))))); // priority
719 cc
->CreationDate() > Time::Now()) << L
"CreationDate too recent";
720 cookies_per_origin_
[CookieOrigin(cc
->Domain(), cc
->IsSecure())]++;
721 cookies
.push_back(cc
.release());
727 base::AutoLock
locked(lock_
);
728 cookies_
.insert(cookies_
.end(), cookies
.begin(), cookies
.end());
733 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
735 if (!meta_table_
.Init(
736 db_
.get(), kCurrentVersionNumber
, kCompatibleVersionNumber
)) {
740 if (meta_table_
.GetCompatibleVersionNumber() > kCurrentVersionNumber
) {
741 LOG(WARNING
) << "Cookie database is too new.";
745 int cur_version
= meta_table_
.GetVersionNumber();
746 if (cur_version
== 2) {
747 sql::Transaction
transaction(db_
.get());
748 if (!transaction
.Begin())
750 if (!db_
->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
751 "INTEGER DEFAULT 0") ||
752 !db_
->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
753 LOG(WARNING
) << "Unable to update cookie database to version 3.";
757 meta_table_
.SetVersionNumber(cur_version
);
758 meta_table_
.SetCompatibleVersionNumber(
759 std::min(cur_version
, kCompatibleVersionNumber
));
760 transaction
.Commit();
763 if (cur_version
== 3) {
764 // The time epoch changed for Mac & Linux in this version to match Windows.
765 // This patch came after the main epoch change happened, so some
766 // developers have "good" times for cookies added by the more recent
767 // versions. So we have to be careful to only update times that are under
768 // the old system (which will appear to be from before 1970 in the new
769 // system). The magic number used below is 1970 in our time units.
770 sql::Transaction
transaction(db_
.get());
773 ignore_result(db_
->Execute(
775 "SET creation_utc = creation_utc + 11644473600000000 "
777 "(SELECT rowid FROM cookies WHERE "
778 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
779 ignore_result(db_
->Execute(
781 "SET expires_utc = expires_utc + 11644473600000000 "
783 "(SELECT rowid FROM cookies WHERE "
784 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
785 ignore_result(db_
->Execute(
787 "SET last_access_utc = last_access_utc + 11644473600000000 "
789 "(SELECT rowid FROM cookies WHERE "
790 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
793 meta_table_
.SetVersionNumber(cur_version
);
794 transaction
.Commit();
797 if (cur_version
== 4) {
798 const base::TimeTicks start_time
= base::TimeTicks::Now();
799 sql::Transaction
transaction(db_
.get());
800 if (!transaction
.Begin())
802 if (!db_
->Execute("ALTER TABLE cookies "
803 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
804 !db_
->Execute("ALTER TABLE cookies "
805 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
806 LOG(WARNING
) << "Unable to update cookie database to version 5.";
810 meta_table_
.SetVersionNumber(cur_version
);
811 meta_table_
.SetCompatibleVersionNumber(
812 std::min(cur_version
, kCompatibleVersionNumber
));
813 transaction
.Commit();
814 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
815 base::TimeTicks::Now() - start_time
);
818 if (cur_version
== 5) {
819 const base::TimeTicks start_time
= base::TimeTicks::Now();
820 sql::Transaction
transaction(db_
.get());
821 if (!transaction
.Begin())
823 // Alter the table to add the priority column with a default value.
824 std::string
stmt(base::StringPrintf(
825 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
826 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT
)));
827 if (!db_
->Execute(stmt
.c_str())) {
828 LOG(WARNING
) << "Unable to update cookie database to version 6.";
832 meta_table_
.SetVersionNumber(cur_version
);
833 meta_table_
.SetCompatibleVersionNumber(
834 std::min(cur_version
, kCompatibleVersionNumber
));
835 transaction
.Commit();
836 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
837 base::TimeTicks::Now() - start_time
);
840 // Put future migration cases here.
842 if (cur_version
< kCurrentVersionNumber
) {
843 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
846 db_
.reset(new sql::Connection
);
847 if (!base::DeleteFile(path_
, false) ||
850 db_
.get(), kCurrentVersionNumber
, kCompatibleVersionNumber
)) {
851 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
852 NOTREACHED() << "Unable to reset the cookie DB.";
862 void SQLitePersistentCookieStore::Backend::AddCookie(
863 const net::CanonicalCookie
& cc
) {
864 BatchOperation(PendingOperation::COOKIE_ADD
, cc
);
867 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
868 const net::CanonicalCookie
& cc
) {
869 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS
, cc
);
872 void SQLitePersistentCookieStore::Backend::DeleteCookie(
873 const net::CanonicalCookie
& cc
) {
874 BatchOperation(PendingOperation::COOKIE_DELETE
, cc
);
877 void SQLitePersistentCookieStore::Backend::BatchOperation(
878 PendingOperation::OperationType op
,
879 const net::CanonicalCookie
& cc
) {
880 // Commit every 30 seconds.
881 static const int kCommitIntervalMs
= 30 * 1000;
882 // Commit right away if we have more than 512 outstanding operations.
883 static const size_t kCommitAfterBatchSize
= 512;
884 DCHECK(!background_task_runner_
->RunsTasksOnCurrentThread());
886 // We do a full copy of the cookie here, and hopefully just here.
887 scoped_ptr
<PendingOperation
> po(new PendingOperation(op
, cc
));
889 PendingOperationsList::size_type num_pending
;
891 base::AutoLock
locked(lock_
);
892 pending_
.push_back(po
.release());
893 num_pending
= ++num_pending_
;
896 if (num_pending
== 1) {
897 // We've gotten our first entry for this batch, fire off the timer.
898 if (!background_task_runner_
->PostDelayedTask(
899 FROM_HERE
, base::Bind(&Backend::Commit
, this),
900 base::TimeDelta::FromMilliseconds(kCommitIntervalMs
))) {
901 NOTREACHED() << "background_task_runner_ is not running.";
903 } else if (num_pending
== kCommitAfterBatchSize
) {
904 // We've reached a big enough batch, fire off a commit now.
905 PostBackgroundTask(FROM_HERE
, base::Bind(&Backend::Commit
, this));
909 void SQLitePersistentCookieStore::Backend::Commit() {
910 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
912 PendingOperationsList ops
;
914 base::AutoLock
locked(lock_
);
919 // Maybe an old timer fired or we are already Close()'ed.
920 if (!db_
.get() || ops
.empty())
923 sql::Statement
add_smt(db_
->GetCachedStatement(SQL_FROM_HERE
,
924 "INSERT INTO cookies (creation_utc, host_key, name, value, path, "
925 "expires_utc, secure, httponly, last_access_utc, has_expires, "
926 "persistent, priority) "
927 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"));
928 if (!add_smt
.is_valid())
931 sql::Statement
update_access_smt(db_
->GetCachedStatement(SQL_FROM_HERE
,
932 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
933 if (!update_access_smt
.is_valid())
936 sql::Statement
del_smt(db_
->GetCachedStatement(SQL_FROM_HERE
,
937 "DELETE FROM cookies WHERE creation_utc=?"));
938 if (!del_smt
.is_valid())
941 sql::Transaction
transaction(db_
.get());
942 if (!transaction
.Begin())
945 for (PendingOperationsList::iterator it
= ops
.begin();
946 it
!= ops
.end(); ++it
) {
947 // Free the cookies as we commit them to the database.
948 scoped_ptr
<PendingOperation
> po(*it
);
950 case PendingOperation::COOKIE_ADD
:
952 CookieOrigin(po
->cc().Domain(), po
->cc().IsSecure())]++;
954 add_smt
.BindInt64(0, po
->cc().CreationDate().ToInternalValue());
955 add_smt
.BindString(1, po
->cc().Domain());
956 add_smt
.BindString(2, po
->cc().Name());
957 add_smt
.BindString(3, po
->cc().Value());
958 add_smt
.BindString(4, po
->cc().Path());
959 add_smt
.BindInt64(5, po
->cc().ExpiryDate().ToInternalValue());
960 add_smt
.BindInt(6, po
->cc().IsSecure());
961 add_smt
.BindInt(7, po
->cc().IsHttpOnly());
962 add_smt
.BindInt64(8, po
->cc().LastAccessDate().ToInternalValue());
963 add_smt
.BindInt(9, po
->cc().IsPersistent());
964 add_smt
.BindInt(10, po
->cc().IsPersistent());
966 11, CookiePriorityToDBCookiePriority(po
->cc().Priority()));
968 NOTREACHED() << "Could not add a cookie to the DB.";
971 case PendingOperation::COOKIE_UPDATEACCESS
:
972 update_access_smt
.Reset(true);
973 update_access_smt
.BindInt64(0,
974 po
->cc().LastAccessDate().ToInternalValue());
975 update_access_smt
.BindInt64(1,
976 po
->cc().CreationDate().ToInternalValue());
977 if (!update_access_smt
.Run())
978 NOTREACHED() << "Could not update cookie last access time in the DB.";
981 case PendingOperation::COOKIE_DELETE
:
983 CookieOrigin(po
->cc().Domain(), po
->cc().IsSecure())]--;
985 del_smt
.BindInt64(0, po
->cc().CreationDate().ToInternalValue());
987 NOTREACHED() << "Could not delete a cookie from the DB.";
995 bool succeeded
= transaction
.Commit();
996 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
997 succeeded
? 0 : 1, 2);
1000 void SQLitePersistentCookieStore::Backend::Flush(
1001 const base::Closure
& callback
) {
1002 DCHECK(!background_task_runner_
->RunsTasksOnCurrentThread());
1003 PostBackgroundTask(FROM_HERE
, base::Bind(&Backend::Commit
, this));
1005 if (!callback
.is_null()) {
1006 // We want the completion task to run immediately after Commit() returns.
1007 // Posting it from here means there is less chance of another task getting
1008 // onto the message queue first, than if we posted it from Commit() itself.
1009 PostBackgroundTask(FROM_HERE
, callback
);
1013 // Fire off a close message to the background runner. We could still have a
1014 // pending commit timer or Load operations holding references on us, but if/when
1015 // this fires we will already have been cleaned up and it will be ignored.
1016 void SQLitePersistentCookieStore::Backend::Close() {
1017 if (background_task_runner_
->RunsTasksOnCurrentThread()) {
1018 InternalBackgroundClose();
1020 // Must close the backend on the background runner.
1021 PostBackgroundTask(FROM_HERE
,
1022 base::Bind(&Backend::InternalBackgroundClose
, this));
1026 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1027 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1028 // Commit any pending operations
1031 if (!force_keep_session_state_
&& special_storage_policy_
.get() &&
1032 special_storage_policy_
->HasSessionOnlyOrigins()) {
1033 DeleteSessionCookiesOnShutdown();
1036 meta_table_
.Reset();
1040 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1041 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1046 if (!special_storage_policy_
.get())
1049 sql::Statement
del_smt(db_
->GetCachedStatement(
1050 SQL_FROM_HERE
, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1051 if (!del_smt
.is_valid()) {
1052 LOG(WARNING
) << "Unable to delete cookies on shutdown.";
1056 sql::Transaction
transaction(db_
.get());
1057 if (!transaction
.Begin()) {
1058 LOG(WARNING
) << "Unable to delete cookies on shutdown.";
1062 for (CookiesPerOriginMap::iterator it
= cookies_per_origin_
.begin();
1063 it
!= cookies_per_origin_
.end(); ++it
) {
1064 if (it
->second
<= 0) {
1065 DCHECK_EQ(0, it
->second
);
1068 const GURL
url(net::cookie_util::CookieOriginToURL(it
->first
.first
,
1070 if (!url
.is_valid() || !special_storage_policy_
->IsStorageSessionOnly(url
))
1073 del_smt
.Reset(true);
1074 del_smt
.BindString(0, it
->first
.first
);
1075 del_smt
.BindInt(1, it
->first
.second
);
1077 NOTREACHED() << "Could not delete a cookie from the DB.";
1080 if (!transaction
.Commit())
1081 LOG(WARNING
) << "Unable to delete cookies on shutdown.";
1084 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1086 sql::Statement
* stmt
) {
1087 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1089 if (!sql::IsErrorCatastrophic(error
))
1092 // TODO(shess): Running KillDatabase() multiple times should be
1094 if (corruption_detected_
)
1097 corruption_detected_
= true;
1099 // Don't just do the close/delete here, as we are being called by |db| and
1100 // that seems dangerous.
1101 // TODO(shess): Consider just calling RazeAndClose() immediately.
1102 // db_ may not be safe to reset at this point, but RazeAndClose()
1103 // would cause the stack to unwind safely with errors.
1104 PostBackgroundTask(FROM_HERE
, base::Bind(&Backend::KillDatabase
, this));
1107 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1108 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1111 // This Backend will now be in-memory only. In a future run we will recreate
1112 // the database. Hopefully things go better then!
1113 bool success
= db_
->RazeAndClose();
1114 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success
);
1115 meta_table_
.Reset();
1120 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1121 base::AutoLock
locked(lock_
);
1122 force_keep_session_state_
= true;
1125 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1126 DCHECK(background_task_runner_
->RunsTasksOnCurrentThread());
1127 if (!db_
->Execute("DELETE FROM cookies WHERE persistent == 0"))
1128 LOG(WARNING
) << "Unable to delete session cookies.";
1131 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1132 const tracked_objects::Location
& origin
, const base::Closure
& task
) {
1133 if (!background_task_runner_
->PostTask(origin
, task
)) {
1134 LOG(WARNING
) << "Failed to post task from " << origin
.ToString()
1135 << " to background_task_runner_.";
1139 void SQLitePersistentCookieStore::Backend::PostClientTask(
1140 const tracked_objects::Location
& origin
, const base::Closure
& task
) {
1141 if (!client_task_runner_
->PostTask(origin
, task
)) {
1142 LOG(WARNING
) << "Failed to post task from " << origin
.ToString()
1143 << " to client_task_runner_.";
1147 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1148 const base::FilePath
& path
,
1149 const scoped_refptr
<base::SequencedTaskRunner
>& client_task_runner
,
1150 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
,
1151 bool restore_old_session_cookies
,
1152 quota::SpecialStoragePolicy
* special_storage_policy
)
1153 : backend_(new Backend(path
,
1155 background_task_runner
,
1156 restore_old_session_cookies
,
1157 special_storage_policy
)) {
1160 void SQLitePersistentCookieStore::Load(const LoadedCallback
& loaded_callback
) {
1161 backend_
->Load(loaded_callback
);
1164 void SQLitePersistentCookieStore::LoadCookiesForKey(
1165 const std::string
& key
,
1166 const LoadedCallback
& loaded_callback
) {
1167 backend_
->LoadCookiesForKey(key
, loaded_callback
);
1170 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie
& cc
) {
1171 backend_
->AddCookie(cc
);
1174 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1175 const net::CanonicalCookie
& cc
) {
1176 backend_
->UpdateCookieAccessTime(cc
);
1179 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie
& cc
) {
1180 backend_
->DeleteCookie(cc
);
1183 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1184 backend_
->SetForceKeepSessionState();
1187 void SQLitePersistentCookieStore::Flush(const base::Closure
& callback
) {
1188 backend_
->Flush(callback
);
1191 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1193 // We release our reference to the Backend, though it will probably still have
1194 // a reference if the background runner has not run Close() yet.
1197 net::CookieStore
* CreatePersistentCookieStore(
1198 const base::FilePath
& path
,
1199 bool restore_old_session_cookies
,
1200 quota::SpecialStoragePolicy
* storage_policy
,
1201 net::CookieMonster::Delegate
* cookie_monster_delegate
,
1202 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
) {
1203 SQLitePersistentCookieStore
* persistent_store
=
1204 new SQLitePersistentCookieStore(
1206 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
),
1207 background_task_runner
.get() ? background_task_runner
:
1208 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1209 BrowserThread::GetBlockingPool()->GetSequenceToken()),
1210 restore_old_session_cookies
,
1212 net::CookieMonster
* cookie_monster
=
1213 new net::CookieMonster(persistent_store
, cookie_monster_delegate
);
1215 const std::string cookie_priority_experiment_group
=
1216 base::FieldTrialList::FindFullName("CookieRetentionPriorityStudy");
1217 cookie_monster
->SetPriorityAwareGarbageCollection(
1218 cookie_priority_experiment_group
== "ExperimentOn");
1220 return cookie_monster
;
1223 } // namespace content