Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(146)

Side by Side Diff: content/browser/net/sqlite_persistent_cookie_store.cc

Issue 1016643004: Moves SQLitePersistentCookieStore to net/extras/sqlite. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@cookies
Patch Set: Better timestamp fix. Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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.
4
5 #include "content/browser/net/sqlite_persistent_cookie_store.h"
6
7 #include <list>
8 #include <map>
9 #include <set>
10 #include <utility>
11
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/callback.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.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/profiler/scoped_tracker.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_store_factory.h"
32 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
33 #include "net/cookies/canonical_cookie.h"
34 #include "net/cookies/cookie_constants.h"
35 #include "net/cookies/cookie_util.h"
36 #include "net/extras/sqlite/cookie_crypto_delegate.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 "storage/browser/quota/special_storage_policy.h"
42 #include "third_party/sqlite/sqlite3.h"
43 #include "url/gurl.h"
44
45 using base::Time;
46
47 namespace {
48
49 // The persistent cookie store is loaded into memory on eTLD at a time. This
50 // variable controls the delay between loading eTLDs, so as to not overload the
51 // CPU or I/O with these low priority requests immediately after start up.
52 const int kLoadDelayMilliseconds = 0;
53
54 } // namespace
55
56 namespace content {
57
58 // This class is designed to be shared between any client thread and the
59 // background task runner. It batches operations and commits them on a timer.
60 //
61 // SQLitePersistentCookieStore::Load is called to load all cookies. It
62 // delegates to Backend::Load, which posts a Backend::LoadAndNotifyOnDBThread
63 // task to the background runner. This task calls Backend::ChainLoadCookies(),
64 // which repeatedly posts itself to the BG runner to load each eTLD+1's cookies
65 // in separate tasks. When this is complete, Backend::CompleteLoadOnIOThread is
66 // posted to the client runner, which notifies the caller of
67 // SQLitePersistentCookieStore::Load that the load is complete.
68 //
69 // If a priority load request is invoked via SQLitePersistentCookieStore::
70 // LoadCookiesForKey, it is delegated to Backend::LoadCookiesForKey, which posts
71 // Backend::LoadKeyAndNotifyOnDBThread to the BG runner. That routine loads just
72 // that single domain key (eTLD+1)'s cookies, and posts a Backend::
73 // CompleteLoadForKeyOnIOThread to the client runner to notify the caller of
74 // SQLitePersistentCookieStore::LoadCookiesForKey that that load is complete.
75 //
76 // Subsequent to loading, mutations may be queued by any thread using
77 // AddCookie, UpdateCookieAccessTime, and DeleteCookie. These are flushed to
78 // disk on the BG runner every 30 seconds, 512 operations, or call to Flush(),
79 // whichever occurs first.
80 class SQLitePersistentCookieStore::Backend
81 : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
82 public:
83 Backend(
84 const base::FilePath& path,
85 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
86 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
87 bool restore_old_session_cookies,
88 storage::SpecialStoragePolicy* special_storage_policy,
89 net::CookieCryptoDelegate* crypto_delegate)
90 : path_(path),
91 num_pending_(0),
92 force_keep_session_state_(false),
93 initialized_(false),
94 corruption_detected_(false),
95 restore_old_session_cookies_(restore_old_session_cookies),
96 special_storage_policy_(special_storage_policy),
97 num_cookies_read_(0),
98 client_task_runner_(client_task_runner),
99 background_task_runner_(background_task_runner),
100 num_priority_waiting_(0),
101 total_priority_requests_(0),
102 crypto_(crypto_delegate) {}
103
104 // Creates or loads the SQLite database.
105 void Load(const LoadedCallback& loaded_callback);
106
107 // Loads cookies for the domain key (eTLD+1).
108 void LoadCookiesForKey(const std::string& domain,
109 const LoadedCallback& loaded_callback);
110
111 // Steps through all results of |smt|, makes a cookie from each, and adds the
112 // cookie to |cookies|. This method also updates |cookies_per_origin_| and
113 // |num_cookies_read_|.
114 void MakeCookiesFromSQLStatement(std::vector<net::CanonicalCookie*>* cookies,
115 sql::Statement* statement);
116
117 // Batch a cookie addition.
118 void AddCookie(const net::CanonicalCookie& cc);
119
120 // Batch a cookie access time update.
121 void UpdateCookieAccessTime(const net::CanonicalCookie& cc);
122
123 // Batch a cookie deletion.
124 void DeleteCookie(const net::CanonicalCookie& cc);
125
126 // Commit pending operations as soon as possible.
127 void Flush(const base::Closure& callback);
128
129 // Commit any pending operations and close the database. This must be called
130 // before the object is destructed.
131 void Close();
132
133 void SetForceKeepSessionState();
134
135 private:
136 friend class base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend>;
137
138 // You should call Close() before destructing this object.
139 ~Backend() {
140 DCHECK(!db_.get()) << "Close should have already been called.";
141 DCHECK(num_pending_ == 0 && pending_.empty());
142
143 for (net::CanonicalCookie* cookie : cookies_) {
144 delete cookie;
145 }
146 }
147
148 // Database upgrade statements.
149 bool EnsureDatabaseVersion();
150
151 class PendingOperation {
152 public:
153 typedef enum {
154 COOKIE_ADD,
155 COOKIE_UPDATEACCESS,
156 COOKIE_DELETE,
157 } OperationType;
158
159 PendingOperation(OperationType op, const net::CanonicalCookie& cc)
160 : op_(op), cc_(cc) { }
161
162 OperationType op() const { return op_; }
163 const net::CanonicalCookie& cc() const { return cc_; }
164
165 private:
166 OperationType op_;
167 net::CanonicalCookie cc_;
168 };
169
170 private:
171 // Creates or loads the SQLite database on background runner.
172 void LoadAndNotifyInBackground(const LoadedCallback& loaded_callback,
173 const base::Time& posted_at);
174
175 // Loads cookies for the domain key (eTLD+1) on background runner.
176 void LoadKeyAndNotifyInBackground(const std::string& domains,
177 const LoadedCallback& loaded_callback,
178 const base::Time& posted_at);
179
180 // Notifies the CookieMonster when loading completes for a specific domain key
181 // or for all domain keys. Triggers the callback and passes it all cookies
182 // that have been loaded from DB since last IO notification.
183 void Notify(const LoadedCallback& loaded_callback, bool load_success);
184
185 // Sends notification when the entire store is loaded, and reports metrics
186 // for the total time to load and aggregated results from any priority loads
187 // that occurred.
188 void CompleteLoadInForeground(const LoadedCallback& loaded_callback,
189 bool load_success);
190
191 // Sends notification when a single priority load completes. Updates priority
192 // load metric data. The data is sent only after the final load completes.
193 void CompleteLoadForKeyInForeground(const LoadedCallback& loaded_callback,
194 bool load_success,
195 const base::Time& requested_at);
196
197 // Sends all metrics, including posting a ReportMetricsInBackground task.
198 // Called after all priority and regular loading is complete.
199 void ReportMetrics();
200
201 // Sends background-runner owned metrics (i.e., the combined duration of all
202 // BG-runner tasks).
203 void ReportMetricsInBackground();
204
205 // Initialize the data base.
206 bool InitializeDatabase();
207
208 // Loads cookies for the next domain key from the DB, then either reschedules
209 // itself or schedules the provided callback to run on the client runner (if
210 // all domains are loaded).
211 void ChainLoadCookies(const LoadedCallback& loaded_callback);
212
213 // Load all cookies for a set of domains/hosts
214 bool LoadCookiesForDomains(const std::set<std::string>& key);
215
216 // Batch a cookie operation (add or delete)
217 void BatchOperation(PendingOperation::OperationType op,
218 const net::CanonicalCookie& cc);
219 // Commit our pending operations to the database.
220 void Commit();
221 // Close() executed on the background runner.
222 void InternalBackgroundClose();
223
224 void DeleteSessionCookiesOnStartup();
225
226 void DeleteSessionCookiesOnShutdown();
227
228 void DatabaseErrorCallback(int error, sql::Statement* stmt);
229 void KillDatabase();
230
231 void PostBackgroundTask(const tracked_objects::Location& origin,
232 const base::Closure& task);
233 void PostClientTask(const tracked_objects::Location& origin,
234 const base::Closure& task);
235
236 // Shared code between the different load strategies to be used after all
237 // cookies have been loaded.
238 void FinishedLoadingCookies(const LoadedCallback& loaded_callback,
239 bool success);
240
241 base::FilePath path_;
242 scoped_ptr<sql::Connection> db_;
243 sql::MetaTable meta_table_;
244
245 typedef std::list<PendingOperation*> PendingOperationsList;
246 PendingOperationsList pending_;
247 PendingOperationsList::size_type num_pending_;
248 // True if the persistent store should skip delete on exit rules.
249 bool force_keep_session_state_;
250 // Guard |cookies_|, |pending_|, |num_pending_|, |force_keep_session_state_|
251 base::Lock lock_;
252
253 // Temporary buffer for cookies loaded from DB. Accumulates cookies to reduce
254 // the number of messages sent to the client runner. Sent back in response to
255 // individual load requests for domain keys or when all loading completes.
256 // Ownership of the cookies in this vector is transferred to the client in
257 // response to individual load requests or when all loading completes.
258 std::vector<net::CanonicalCookie*> cookies_;
259
260 // Map of domain keys(eTLD+1) to domains/hosts that are to be loaded from DB.
261 std::map<std::string, std::set<std::string> > keys_to_load_;
262
263 // Map of (domain keys(eTLD+1), is secure cookie) to number of cookies in the
264 // database.
265 typedef std::pair<std::string, bool> CookieOrigin;
266 typedef std::map<CookieOrigin, int> CookiesPerOriginMap;
267 CookiesPerOriginMap cookies_per_origin_;
268
269 // Indicates if DB has been initialized.
270 bool initialized_;
271
272 // Indicates if the kill-database callback has been scheduled.
273 bool corruption_detected_;
274
275 // If false, we should filter out session cookies when reading the DB.
276 bool restore_old_session_cookies_;
277
278 // Policy defining what data is deleted on shutdown.
279 scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_;
280
281 // The cumulative time spent loading the cookies on the background runner.
282 // Incremented and reported from the background runner.
283 base::TimeDelta cookie_load_duration_;
284
285 // The total number of cookies read. Incremented and reported on the
286 // background runner.
287 int num_cookies_read_;
288
289 scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
290 scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
291
292 // Guards the following metrics-related properties (only accessed when
293 // starting/completing priority loads or completing the total load).
294 base::Lock metrics_lock_;
295 int num_priority_waiting_;
296 // The total number of priority requests.
297 int total_priority_requests_;
298 // The time when |num_priority_waiting_| incremented to 1.
299 base::Time current_priority_wait_start_;
300 // The cumulative duration of time when |num_priority_waiting_| was greater
301 // than 1.
302 base::TimeDelta priority_wait_duration_;
303 // Class with functions that do cryptographic operations (for protecting
304 // cookies stored persistently).
305 //
306 // Not owned.
307 net::CookieCryptoDelegate* crypto_;
308
309 DISALLOW_COPY_AND_ASSIGN(Backend);
310 };
311
312 namespace {
313
314 // Version number of the database.
315 //
316 // Version 9 adds a partial index to track non-persistent cookies.
317 // Non-persistent cookies sometimes need to be deleted on startup. There are
318 // frequently few or no non-persistent cookies, so the partial index allows the
319 // deletion to be sped up or skipped, without having to page in the DB.
320 //
321 // Version 8 adds "first-party only" cookies.
322 //
323 // Version 7 adds encrypted values. Old values will continue to be used but
324 // all new values written will be encrypted on selected operating systems. New
325 // records read by old clients will simply get an empty cookie value while old
326 // records read by new clients will continue to operate with the unencrypted
327 // version. New and old clients alike will always write/update records with
328 // what they support.
329 //
330 // Version 6 adds cookie priorities. This allows developers to influence the
331 // order in which cookies are evicted in order to meet domain cookie limits.
332 //
333 // Version 5 adds the columns has_expires and is_persistent, so that the
334 // database can store session cookies as well as persistent cookies. Databases
335 // of version 5 are incompatible with older versions of code. If a database of
336 // version 5 is read by older code, session cookies will be treated as normal
337 // cookies. Currently, these fields are written, but not read anymore.
338 //
339 // In version 4, we migrated the time epoch. If you open the DB with an older
340 // version on Mac or Linux, the times will look wonky, but the file will likely
341 // be usable. On Windows version 3 and 4 are the same.
342 //
343 // Version 3 updated the database to include the last access time, so we can
344 // expire them in decreasing order of use when we've reached the maximum
345 // number of cookies.
346 const int kCurrentVersionNumber = 9;
347 const int kCompatibleVersionNumber = 5;
348
349 // Possible values for the 'priority' column.
350 enum DBCookiePriority {
351 kCookiePriorityLow = 0,
352 kCookiePriorityMedium = 1,
353 kCookiePriorityHigh = 2,
354 };
355
356 DBCookiePriority CookiePriorityToDBCookiePriority(net::CookiePriority value) {
357 switch (value) {
358 case net::COOKIE_PRIORITY_LOW:
359 return kCookiePriorityLow;
360 case net::COOKIE_PRIORITY_MEDIUM:
361 return kCookiePriorityMedium;
362 case net::COOKIE_PRIORITY_HIGH:
363 return kCookiePriorityHigh;
364 }
365
366 NOTREACHED();
367 return kCookiePriorityMedium;
368 }
369
370 net::CookiePriority DBCookiePriorityToCookiePriority(DBCookiePriority value) {
371 switch (value) {
372 case kCookiePriorityLow:
373 return net::COOKIE_PRIORITY_LOW;
374 case kCookiePriorityMedium:
375 return net::COOKIE_PRIORITY_MEDIUM;
376 case kCookiePriorityHigh:
377 return net::COOKIE_PRIORITY_HIGH;
378 }
379
380 NOTREACHED();
381 return net::COOKIE_PRIORITY_DEFAULT;
382 }
383
384 // Increments a specified TimeDelta by the duration between this object's
385 // constructor and destructor. Not thread safe. Multiple instances may be
386 // created with the same delta instance as long as their lifetimes are nested.
387 // The shortest lived instances have no impact.
388 class IncrementTimeDelta {
389 public:
390 explicit IncrementTimeDelta(base::TimeDelta* delta) :
391 delta_(delta),
392 original_value_(*delta),
393 start_(base::Time::Now()) {}
394
395 ~IncrementTimeDelta() {
396 *delta_ = original_value_ + base::Time::Now() - start_;
397 }
398
399 private:
400 base::TimeDelta* delta_;
401 base::TimeDelta original_value_;
402 base::Time start_;
403
404 DISALLOW_COPY_AND_ASSIGN(IncrementTimeDelta);
405 };
406
407 // Initializes the cookies table, returning true on success.
408 bool InitTable(sql::Connection* db) {
409 if (db->DoesTableExist("cookies"))
410 return true;
411
412 std::string stmt(base::StringPrintf(
413 "CREATE TABLE cookies ("
414 "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
415 "host_key TEXT NOT NULL,"
416 "name TEXT NOT NULL,"
417 "value TEXT NOT NULL,"
418 "path TEXT NOT NULL,"
419 "expires_utc INTEGER NOT NULL,"
420 "secure INTEGER NOT NULL,"
421 "httponly INTEGER NOT NULL,"
422 "last_access_utc INTEGER NOT NULL, "
423 "has_expires INTEGER NOT NULL DEFAULT 1, "
424 "persistent INTEGER NOT NULL DEFAULT 1,"
425 "priority INTEGER NOT NULL DEFAULT %d,"
426 "encrypted_value BLOB DEFAULT '',"
427 "firstpartyonly INTEGER NOT NULL DEFAULT 0)",
428 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
429 if (!db->Execute(stmt.c_str()))
430 return false;
431
432 if (!db->Execute("CREATE INDEX domain ON cookies(host_key)"))
433 return false;
434
435 #if defined(OS_IOS)
436 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
437 // partial indices.
438 if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) {
439 #else
440 if (!db->Execute(
441 "CREATE INDEX is_transient ON cookies(persistent) "
442 "where persistent != 1")) {
443 #endif
444 return false;
445 }
446
447 return true;
448 }
449
450 } // namespace
451
452 void SQLitePersistentCookieStore::Backend::Load(
453 const LoadedCallback& loaded_callback) {
454 // This function should be called only once per instance.
455 DCHECK(!db_.get());
456 PostBackgroundTask(FROM_HERE, base::Bind(
457 &Backend::LoadAndNotifyInBackground, this,
458 loaded_callback, base::Time::Now()));
459 }
460
461 void SQLitePersistentCookieStore::Backend::LoadCookiesForKey(
462 const std::string& key,
463 const LoadedCallback& loaded_callback) {
464 {
465 base::AutoLock locked(metrics_lock_);
466 if (num_priority_waiting_ == 0)
467 current_priority_wait_start_ = base::Time::Now();
468 num_priority_waiting_++;
469 total_priority_requests_++;
470 }
471
472 PostBackgroundTask(FROM_HERE, base::Bind(
473 &Backend::LoadKeyAndNotifyInBackground,
474 this, key, loaded_callback, base::Time::Now()));
475 }
476
477 void SQLitePersistentCookieStore::Backend::LoadAndNotifyInBackground(
478 const LoadedCallback& loaded_callback, const base::Time& posted_at) {
479 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
480 IncrementTimeDelta increment(&cookie_load_duration_);
481
482 UMA_HISTOGRAM_CUSTOM_TIMES(
483 "Cookie.TimeLoadDBQueueWait",
484 base::Time::Now() - posted_at,
485 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
486 50);
487
488 if (!InitializeDatabase()) {
489 PostClientTask(FROM_HERE, base::Bind(
490 &Backend::CompleteLoadInForeground, this, loaded_callback, false));
491 } else {
492 ChainLoadCookies(loaded_callback);
493 }
494 }
495
496 void SQLitePersistentCookieStore::Backend::LoadKeyAndNotifyInBackground(
497 const std::string& key,
498 const LoadedCallback& loaded_callback,
499 const base::Time& posted_at) {
500 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
501 IncrementTimeDelta increment(&cookie_load_duration_);
502
503 UMA_HISTOGRAM_CUSTOM_TIMES(
504 "Cookie.TimeKeyLoadDBQueueWait",
505 base::Time::Now() - posted_at,
506 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
507 50);
508
509 bool success = false;
510 if (InitializeDatabase()) {
511 std::map<std::string, std::set<std::string> >::iterator
512 it = keys_to_load_.find(key);
513 if (it != keys_to_load_.end()) {
514 success = LoadCookiesForDomains(it->second);
515 keys_to_load_.erase(it);
516 } else {
517 success = true;
518 }
519 }
520
521 PostClientTask(FROM_HERE, base::Bind(
522 &SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground,
523 this, loaded_callback, success, posted_at));
524 }
525
526 void SQLitePersistentCookieStore::Backend::CompleteLoadForKeyInForeground(
527 const LoadedCallback& loaded_callback,
528 bool load_success,
529 const::Time& requested_at) {
530 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
531
532 UMA_HISTOGRAM_CUSTOM_TIMES(
533 "Cookie.TimeKeyLoadTotalWait",
534 base::Time::Now() - requested_at,
535 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
536 50);
537
538 Notify(loaded_callback, load_success);
539
540 {
541 base::AutoLock locked(metrics_lock_);
542 num_priority_waiting_--;
543 if (num_priority_waiting_ == 0) {
544 priority_wait_duration_ +=
545 base::Time::Now() - current_priority_wait_start_;
546 }
547 }
548
549 }
550
551 void SQLitePersistentCookieStore::Backend::ReportMetricsInBackground() {
552 UMA_HISTOGRAM_CUSTOM_TIMES(
553 "Cookie.TimeLoad",
554 cookie_load_duration_,
555 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
556 50);
557 }
558
559 void SQLitePersistentCookieStore::Backend::ReportMetrics() {
560 PostBackgroundTask(FROM_HERE, base::Bind(
561 &SQLitePersistentCookieStore::Backend::ReportMetricsInBackground, this));
562
563 {
564 base::AutoLock locked(metrics_lock_);
565 UMA_HISTOGRAM_CUSTOM_TIMES(
566 "Cookie.PriorityBlockingTime",
567 priority_wait_duration_,
568 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
569 50);
570
571 UMA_HISTOGRAM_COUNTS_100(
572 "Cookie.PriorityLoadCount",
573 total_priority_requests_);
574
575 UMA_HISTOGRAM_COUNTS_10000(
576 "Cookie.NumberOfLoadedCookies",
577 num_cookies_read_);
578 }
579 }
580
581 void SQLitePersistentCookieStore::Backend::CompleteLoadInForeground(
582 const LoadedCallback& loaded_callback, bool load_success) {
583 Notify(loaded_callback, load_success);
584
585 if (load_success)
586 ReportMetrics();
587 }
588
589 void SQLitePersistentCookieStore::Backend::Notify(
590 const LoadedCallback& loaded_callback,
591 bool load_success) {
592 DCHECK(client_task_runner_->RunsTasksOnCurrentThread());
593
594 std::vector<net::CanonicalCookie*> cookies;
595 {
596 base::AutoLock locked(lock_);
597 cookies.swap(cookies_);
598 }
599
600 loaded_callback.Run(cookies);
601 }
602
603 bool SQLitePersistentCookieStore::Backend::InitializeDatabase() {
604 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
605
606 if (initialized_ || corruption_detected_) {
607 // Return false if we were previously initialized but the DB has since been
608 // closed, or if corruption caused a database reset during initialization.
609 return db_ != NULL;
610 }
611
612 base::Time start = base::Time::Now();
613
614 const base::FilePath dir = path_.DirName();
615 if (!base::PathExists(dir) && !base::CreateDirectory(dir)) {
616 return false;
617 }
618
619 int64 db_size = 0;
620 if (base::GetFileSize(path_, &db_size))
621 UMA_HISTOGRAM_COUNTS("Cookie.DBSizeInKB", db_size / 1024 );
622
623 db_.reset(new sql::Connection);
624 db_->set_histogram_tag("Cookie");
625
626 // Unretained to avoid a ref loop with |db_|.
627 db_->set_error_callback(
628 base::Bind(&SQLitePersistentCookieStore::Backend::DatabaseErrorCallback,
629 base::Unretained(this)));
630
631 if (!db_->Open(path_)) {
632 NOTREACHED() << "Unable to open cookie DB.";
633 if (corruption_detected_)
634 db_->Raze();
635 meta_table_.Reset();
636 db_.reset();
637 return false;
638 }
639
640 if (!EnsureDatabaseVersion() || !InitTable(db_.get())) {
641 NOTREACHED() << "Unable to open cookie DB.";
642 if (corruption_detected_)
643 db_->Raze();
644 meta_table_.Reset();
645 db_.reset();
646 return false;
647 }
648
649 UMA_HISTOGRAM_CUSTOM_TIMES(
650 "Cookie.TimeInitializeDB",
651 base::Time::Now() - start,
652 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
653 50);
654
655 start = base::Time::Now();
656
657 // Retrieve all the domains
658 sql::Statement smt(db_->GetUniqueStatement(
659 "SELECT DISTINCT host_key FROM cookies"));
660
661 if (!smt.is_valid()) {
662 if (corruption_detected_)
663 db_->Raze();
664 meta_table_.Reset();
665 db_.reset();
666 return false;
667 }
668
669 std::vector<std::string> host_keys;
670 while (smt.Step())
671 host_keys.push_back(smt.ColumnString(0));
672
673 UMA_HISTOGRAM_CUSTOM_TIMES(
674 "Cookie.TimeLoadDomains",
675 base::Time::Now() - start,
676 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
677 50);
678
679 base::Time start_parse = base::Time::Now();
680
681 // Build a map of domain keys (always eTLD+1) to domains.
682 for (size_t idx = 0; idx < host_keys.size(); ++idx) {
683 const std::string& domain = host_keys[idx];
684 std::string key =
685 net::registry_controlled_domains::GetDomainAndRegistry(
686 domain,
687 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
688
689 keys_to_load_[key].insert(domain);
690 }
691
692 UMA_HISTOGRAM_CUSTOM_TIMES(
693 "Cookie.TimeParseDomains",
694 base::Time::Now() - start_parse,
695 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
696 50);
697
698 UMA_HISTOGRAM_CUSTOM_TIMES(
699 "Cookie.TimeInitializeDomainMap",
700 base::Time::Now() - start,
701 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
702 50);
703
704 initialized_ = true;
705
706 if (!restore_old_session_cookies_)
707 DeleteSessionCookiesOnStartup();
708 return true;
709 }
710
711 void SQLitePersistentCookieStore::Backend::ChainLoadCookies(
712 const LoadedCallback& loaded_callback) {
713 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
714 IncrementTimeDelta increment(&cookie_load_duration_);
715
716 bool load_success = true;
717
718 if (!db_) {
719 // Close() has been called on this store.
720 load_success = false;
721 } else if (keys_to_load_.size() > 0) {
722 // Load cookies for the first domain key.
723 std::map<std::string, std::set<std::string> >::iterator
724 it = keys_to_load_.begin();
725 load_success = LoadCookiesForDomains(it->second);
726 keys_to_load_.erase(it);
727 }
728
729 // If load is successful and there are more domain keys to be loaded,
730 // then post a background task to continue chain-load;
731 // Otherwise notify on client runner.
732 if (load_success && keys_to_load_.size() > 0) {
733 bool success = background_task_runner_->PostDelayedTask(
734 FROM_HERE,
735 base::Bind(&Backend::ChainLoadCookies, this, loaded_callback),
736 base::TimeDelta::FromMilliseconds(kLoadDelayMilliseconds));
737 if (!success) {
738 LOG(WARNING) << "Failed to post task from " << FROM_HERE.ToString()
739 << " to background_task_runner_.";
740 }
741 } else {
742 FinishedLoadingCookies(loaded_callback, load_success);
743 }
744 }
745
746 bool SQLitePersistentCookieStore::Backend::LoadCookiesForDomains(
747 const std::set<std::string>& domains) {
748 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
749
750 sql::Statement smt;
751 if (restore_old_session_cookies_) {
752 smt.Assign(db_->GetCachedStatement(
753 SQL_FROM_HERE,
754 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
755 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
756 "has_expires, persistent, priority FROM cookies WHERE host_key = ?"));
757 } else {
758 smt.Assign(db_->GetCachedStatement(
759 SQL_FROM_HERE,
760 "SELECT creation_utc, host_key, name, value, encrypted_value, path, "
761 "expires_utc, secure, httponly, firstpartyonly, last_access_utc, "
762 "has_expires, persistent, priority FROM cookies WHERE host_key = ? "
763 "AND persistent = 1"));
764 }
765 if (!smt.is_valid()) {
766 smt.Clear(); // Disconnect smt_ref from db_.
767 meta_table_.Reset();
768 db_.reset();
769 return false;
770 }
771
772 std::vector<net::CanonicalCookie*> cookies;
773 std::set<std::string>::const_iterator it = domains.begin();
774 for (; it != domains.end(); ++it) {
775 smt.BindString(0, *it);
776 MakeCookiesFromSQLStatement(&cookies, &smt);
777 smt.Reset(true);
778 }
779 {
780 base::AutoLock locked(lock_);
781 cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
782 }
783 return true;
784 }
785
786 void SQLitePersistentCookieStore::Backend::MakeCookiesFromSQLStatement(
787 std::vector<net::CanonicalCookie*>* cookies,
788 sql::Statement* statement) {
789 sql::Statement& smt = *statement;
790 while (smt.Step()) {
791 std::string value;
792 std::string encrypted_value = smt.ColumnString(4);
793 if (!encrypted_value.empty() && crypto_) {
794 crypto_->DecryptString(encrypted_value, &value);
795 } else {
796 DCHECK(encrypted_value.empty());
797 value = smt.ColumnString(3);
798 }
799 scoped_ptr<net::CanonicalCookie> cc(new net::CanonicalCookie(
800 // The "source" URL is not used with persisted cookies.
801 GURL(), // Source
802 smt.ColumnString(2), // name
803 value, // value
804 smt.ColumnString(1), // domain
805 smt.ColumnString(5), // path
806 Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc
807 Time::FromInternalValue(smt.ColumnInt64(6)), // expires_utc
808 Time::FromInternalValue(smt.ColumnInt64(10)), // last_access_utc
809 smt.ColumnInt(7) != 0, // secure
810 smt.ColumnInt(8) != 0, // httponly
811 smt.ColumnInt(9) != 0, // firstpartyonly
812 DBCookiePriorityToCookiePriority(
813 static_cast<DBCookiePriority>(smt.ColumnInt(13))))); // priority
814 DLOG_IF(WARNING, cc->CreationDate() > Time::Now())
815 << L"CreationDate too recent";
816 cookies_per_origin_[CookieOrigin(cc->Domain(), cc->IsSecure())]++;
817 cookies->push_back(cc.release());
818 ++num_cookies_read_;
819 }
820 }
821
822 bool SQLitePersistentCookieStore::Backend::EnsureDatabaseVersion() {
823 // Version check.
824 if (!meta_table_.Init(
825 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
826 return false;
827 }
828
829 if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
830 LOG(WARNING) << "Cookie database is too new.";
831 return false;
832 }
833
834 int cur_version = meta_table_.GetVersionNumber();
835 if (cur_version == 2) {
836 sql::Transaction transaction(db_.get());
837 if (!transaction.Begin())
838 return false;
839 if (!db_->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc "
840 "INTEGER DEFAULT 0") ||
841 !db_->Execute("UPDATE cookies SET last_access_utc = creation_utc")) {
842 LOG(WARNING) << "Unable to update cookie database to version 3.";
843 return false;
844 }
845 ++cur_version;
846 meta_table_.SetVersionNumber(cur_version);
847 meta_table_.SetCompatibleVersionNumber(
848 std::min(cur_version, kCompatibleVersionNumber));
849 transaction.Commit();
850 }
851
852 if (cur_version == 3) {
853 // The time epoch changed for Mac & Linux in this version to match Windows.
854 // This patch came after the main epoch change happened, so some
855 // developers have "good" times for cookies added by the more recent
856 // versions. So we have to be careful to only update times that are under
857 // the old system (which will appear to be from before 1970 in the new
858 // system). The magic number used below is 1970 in our time units.
859 sql::Transaction transaction(db_.get());
860 transaction.Begin();
861 #if !defined(OS_WIN)
862 ignore_result(db_->Execute(
863 "UPDATE cookies "
864 "SET creation_utc = creation_utc + 11644473600000000 "
865 "WHERE rowid IN "
866 "(SELECT rowid FROM cookies WHERE "
867 "creation_utc > 0 AND creation_utc < 11644473600000000)"));
868 ignore_result(db_->Execute(
869 "UPDATE cookies "
870 "SET expires_utc = expires_utc + 11644473600000000 "
871 "WHERE rowid IN "
872 "(SELECT rowid FROM cookies WHERE "
873 "expires_utc > 0 AND expires_utc < 11644473600000000)"));
874 ignore_result(db_->Execute(
875 "UPDATE cookies "
876 "SET last_access_utc = last_access_utc + 11644473600000000 "
877 "WHERE rowid IN "
878 "(SELECT rowid FROM cookies WHERE "
879 "last_access_utc > 0 AND last_access_utc < 11644473600000000)"));
880 #endif
881 ++cur_version;
882 meta_table_.SetVersionNumber(cur_version);
883 transaction.Commit();
884 }
885
886 if (cur_version == 4) {
887 const base::TimeTicks start_time = base::TimeTicks::Now();
888 sql::Transaction transaction(db_.get());
889 if (!transaction.Begin())
890 return false;
891 if (!db_->Execute("ALTER TABLE cookies "
892 "ADD COLUMN has_expires INTEGER DEFAULT 1") ||
893 !db_->Execute("ALTER TABLE cookies "
894 "ADD COLUMN persistent INTEGER DEFAULT 1")) {
895 LOG(WARNING) << "Unable to update cookie database to version 5.";
896 return false;
897 }
898 ++cur_version;
899 meta_table_.SetVersionNumber(cur_version);
900 meta_table_.SetCompatibleVersionNumber(
901 std::min(cur_version, kCompatibleVersionNumber));
902 transaction.Commit();
903 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV5",
904 base::TimeTicks::Now() - start_time);
905 }
906
907 if (cur_version == 5) {
908 const base::TimeTicks start_time = base::TimeTicks::Now();
909 sql::Transaction transaction(db_.get());
910 if (!transaction.Begin())
911 return false;
912 // Alter the table to add the priority column with a default value.
913 std::string stmt(base::StringPrintf(
914 "ALTER TABLE cookies ADD COLUMN priority INTEGER DEFAULT %d",
915 CookiePriorityToDBCookiePriority(net::COOKIE_PRIORITY_DEFAULT)));
916 if (!db_->Execute(stmt.c_str())) {
917 LOG(WARNING) << "Unable to update cookie database to version 6.";
918 return false;
919 }
920 ++cur_version;
921 meta_table_.SetVersionNumber(cur_version);
922 meta_table_.SetCompatibleVersionNumber(
923 std::min(cur_version, kCompatibleVersionNumber));
924 transaction.Commit();
925 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV6",
926 base::TimeTicks::Now() - start_time);
927 }
928
929 if (cur_version == 6) {
930 const base::TimeTicks start_time = base::TimeTicks::Now();
931 sql::Transaction transaction(db_.get());
932 if (!transaction.Begin())
933 return false;
934 // Alter the table to add empty "encrypted value" column.
935 if (!db_->Execute("ALTER TABLE cookies "
936 "ADD COLUMN encrypted_value BLOB DEFAULT ''")) {
937 LOG(WARNING) << "Unable to update cookie database to version 7.";
938 return false;
939 }
940 ++cur_version;
941 meta_table_.SetVersionNumber(cur_version);
942 meta_table_.SetCompatibleVersionNumber(
943 std::min(cur_version, kCompatibleVersionNumber));
944 transaction.Commit();
945 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV7",
946 base::TimeTicks::Now() - start_time);
947 }
948
949 if (cur_version == 7) {
950 const base::TimeTicks start_time = base::TimeTicks::Now();
951 sql::Transaction transaction(db_.get());
952 if (!transaction.Begin())
953 return false;
954 // Alter the table to add a 'firstpartyonly' column.
955 if (!db_->Execute(
956 "ALTER TABLE cookies "
957 "ADD COLUMN firstpartyonly INTEGER DEFAULT 0")) {
958 LOG(WARNING) << "Unable to update cookie database to version 8.";
959 return false;
960 }
961 ++cur_version;
962 meta_table_.SetVersionNumber(cur_version);
963 meta_table_.SetCompatibleVersionNumber(
964 std::min(cur_version, kCompatibleVersionNumber));
965 transaction.Commit();
966 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV8",
967 base::TimeTicks::Now() - start_time);
968 }
969
970 if (cur_version == 8) {
971 const base::TimeTicks start_time = base::TimeTicks::Now();
972 sql::Transaction transaction(db_.get());
973 if (!transaction.Begin())
974 return false;
975
976 if (!db_->Execute("DROP INDEX IF EXISTS cookie_times")) {
977 LOG(WARNING)
978 << "Unable to drop table cookie_times in update to version 9.";
979 return false;
980 }
981
982 if (!db_->Execute(
983 "CREATE INDEX IF NOT EXISTS domain ON cookies(host_key)")) {
984 LOG(WARNING) << "Unable to create index domain in update to version 9.";
985 return false;
986 }
987
988 #if defined(OS_IOS)
989 // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports
990 // partial indices.
991 if (!db_->Execute(
992 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent)")) {
993 #else
994 if (!db_->Execute(
995 "CREATE INDEX IF NOT EXISTS is_transient ON cookies(persistent) "
996 "where persistent != 1")) {
997 #endif
998 LOG(WARNING)
999 << "Unable to create index is_transient in update to version 9.";
1000 return false;
1001 }
1002 ++cur_version;
1003 meta_table_.SetVersionNumber(cur_version);
1004 meta_table_.SetCompatibleVersionNumber(
1005 std::min(cur_version, kCompatibleVersionNumber));
1006 transaction.Commit();
1007 UMA_HISTOGRAM_TIMES("Cookie.TimeDatabaseMigrationToV9",
1008 base::TimeTicks::Now() - start_time);
1009 }
1010
1011 // Put future migration cases here.
1012
1013 if (cur_version < kCurrentVersionNumber) {
1014 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTable", 1);
1015
1016 meta_table_.Reset();
1017 db_.reset(new sql::Connection);
1018 if (!sql::Connection::Delete(path_) ||
1019 !db_->Open(path_) ||
1020 !meta_table_.Init(
1021 db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) {
1022 UMA_HISTOGRAM_COUNTS_100("Cookie.CorruptMetaTableRecoveryFailed", 1);
1023 NOTREACHED() << "Unable to reset the cookie DB.";
1024 meta_table_.Reset();
1025 db_.reset();
1026 return false;
1027 }
1028 }
1029
1030 return true;
1031 }
1032
1033 void SQLitePersistentCookieStore::Backend::AddCookie(
1034 const net::CanonicalCookie& cc) {
1035 BatchOperation(PendingOperation::COOKIE_ADD, cc);
1036 }
1037
1038 void SQLitePersistentCookieStore::Backend::UpdateCookieAccessTime(
1039 const net::CanonicalCookie& cc) {
1040 BatchOperation(PendingOperation::COOKIE_UPDATEACCESS, cc);
1041 }
1042
1043 void SQLitePersistentCookieStore::Backend::DeleteCookie(
1044 const net::CanonicalCookie& cc) {
1045 BatchOperation(PendingOperation::COOKIE_DELETE, cc);
1046 }
1047
1048 void SQLitePersistentCookieStore::Backend::BatchOperation(
1049 PendingOperation::OperationType op,
1050 const net::CanonicalCookie& cc) {
1051 // Commit every 30 seconds.
1052 static const int kCommitIntervalMs = 30 * 1000;
1053 // Commit right away if we have more than 512 outstanding operations.
1054 static const size_t kCommitAfterBatchSize = 512;
1055 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1056
1057 // We do a full copy of the cookie here, and hopefully just here.
1058 scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
1059
1060 PendingOperationsList::size_type num_pending;
1061 {
1062 base::AutoLock locked(lock_);
1063 pending_.push_back(po.release());
1064 num_pending = ++num_pending_;
1065 }
1066
1067 if (num_pending == 1) {
1068 // We've gotten our first entry for this batch, fire off the timer.
1069 if (!background_task_runner_->PostDelayedTask(
1070 FROM_HERE, base::Bind(&Backend::Commit, this),
1071 base::TimeDelta::FromMilliseconds(kCommitIntervalMs))) {
1072 NOTREACHED() << "background_task_runner_ is not running.";
1073 }
1074 } else if (num_pending == kCommitAfterBatchSize) {
1075 // We've reached a big enough batch, fire off a commit now.
1076 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1077 }
1078 }
1079
1080 void SQLitePersistentCookieStore::Backend::Commit() {
1081 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1082
1083 PendingOperationsList ops;
1084 {
1085 base::AutoLock locked(lock_);
1086 pending_.swap(ops);
1087 num_pending_ = 0;
1088 }
1089
1090 // Maybe an old timer fired or we are already Close()'ed.
1091 if (!db_.get() || ops.empty())
1092 return;
1093
1094 sql::Statement add_smt(db_->GetCachedStatement(
1095 SQL_FROM_HERE,
1096 "INSERT INTO cookies (creation_utc, host_key, name, value, "
1097 "encrypted_value, path, expires_utc, secure, httponly, firstpartyonly, "
1098 "last_access_utc, has_expires, persistent, priority) "
1099 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
1100 if (!add_smt.is_valid())
1101 return;
1102
1103 sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1104 "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?"));
1105 if (!update_access_smt.is_valid())
1106 return;
1107
1108 sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE,
1109 "DELETE FROM cookies WHERE creation_utc=?"));
1110 if (!del_smt.is_valid())
1111 return;
1112
1113 sql::Transaction transaction(db_.get());
1114 if (!transaction.Begin())
1115 return;
1116
1117 for (PendingOperationsList::iterator it = ops.begin();
1118 it != ops.end(); ++it) {
1119 // Free the cookies as we commit them to the database.
1120 scoped_ptr<PendingOperation> po(*it);
1121 switch (po->op()) {
1122 case PendingOperation::COOKIE_ADD:
1123 cookies_per_origin_[
1124 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]++;
1125 add_smt.Reset(true);
1126 add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1127 add_smt.BindString(1, po->cc().Domain());
1128 add_smt.BindString(2, po->cc().Name());
1129 if (crypto_) {
1130 std::string encrypted_value;
1131 add_smt.BindCString(3, ""); // value
1132 crypto_->EncryptString(po->cc().Value(), &encrypted_value);
1133 // BindBlob() immediately makes an internal copy of the data.
1134 add_smt.BindBlob(4, encrypted_value.data(),
1135 static_cast<int>(encrypted_value.length()));
1136 } else {
1137 add_smt.BindString(3, po->cc().Value());
1138 add_smt.BindBlob(4, "", 0); // encrypted_value
1139 }
1140 add_smt.BindString(5, po->cc().Path());
1141 add_smt.BindInt64(6, po->cc().ExpiryDate().ToInternalValue());
1142 add_smt.BindInt(7, po->cc().IsSecure());
1143 add_smt.BindInt(8, po->cc().IsHttpOnly());
1144 add_smt.BindInt(9, po->cc().IsFirstPartyOnly());
1145 add_smt.BindInt64(10, po->cc().LastAccessDate().ToInternalValue());
1146 add_smt.BindInt(11, po->cc().IsPersistent());
1147 add_smt.BindInt(12, po->cc().IsPersistent());
1148 add_smt.BindInt(13,
1149 CookiePriorityToDBCookiePriority(po->cc().Priority()));
1150 if (!add_smt.Run())
1151 NOTREACHED() << "Could not add a cookie to the DB.";
1152 break;
1153
1154 case PendingOperation::COOKIE_UPDATEACCESS:
1155 update_access_smt.Reset(true);
1156 update_access_smt.BindInt64(0,
1157 po->cc().LastAccessDate().ToInternalValue());
1158 update_access_smt.BindInt64(1,
1159 po->cc().CreationDate().ToInternalValue());
1160 if (!update_access_smt.Run())
1161 NOTREACHED() << "Could not update cookie last access time in the DB.";
1162 break;
1163
1164 case PendingOperation::COOKIE_DELETE:
1165 cookies_per_origin_[
1166 CookieOrigin(po->cc().Domain(), po->cc().IsSecure())]--;
1167 del_smt.Reset(true);
1168 del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue());
1169 if (!del_smt.Run())
1170 NOTREACHED() << "Could not delete a cookie from the DB.";
1171 break;
1172
1173 default:
1174 NOTREACHED();
1175 break;
1176 }
1177 }
1178 bool succeeded = transaction.Commit();
1179 UMA_HISTOGRAM_ENUMERATION("Cookie.BackingStoreUpdateResults",
1180 succeeded ? 0 : 1, 2);
1181 }
1182
1183 void SQLitePersistentCookieStore::Backend::Flush(
1184 const base::Closure& callback) {
1185 DCHECK(!background_task_runner_->RunsTasksOnCurrentThread());
1186 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::Commit, this));
1187
1188 if (!callback.is_null()) {
1189 // We want the completion task to run immediately after Commit() returns.
1190 // Posting it from here means there is less chance of another task getting
1191 // onto the message queue first, than if we posted it from Commit() itself.
1192 PostBackgroundTask(FROM_HERE, callback);
1193 }
1194 }
1195
1196 // Fire off a close message to the background runner. We could still have a
1197 // pending commit timer or Load operations holding references on us, but if/when
1198 // this fires we will already have been cleaned up and it will be ignored.
1199 void SQLitePersistentCookieStore::Backend::Close() {
1200 if (background_task_runner_->RunsTasksOnCurrentThread()) {
1201 InternalBackgroundClose();
1202 } else {
1203 // Must close the backend on the background runner.
1204 PostBackgroundTask(FROM_HERE,
1205 base::Bind(&Backend::InternalBackgroundClose, this));
1206 }
1207 }
1208
1209 void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
1210 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1211 // Commit any pending operations
1212 Commit();
1213
1214 if (!force_keep_session_state_ && special_storage_policy_.get() &&
1215 special_storage_policy_->HasSessionOnlyOrigins()) {
1216 DeleteSessionCookiesOnShutdown();
1217 }
1218
1219 meta_table_.Reset();
1220 db_.reset();
1221 }
1222
1223 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnShutdown() {
1224 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1225
1226 if (!db_)
1227 return;
1228
1229 if (!special_storage_policy_.get())
1230 return;
1231
1232 sql::Statement del_smt(db_->GetCachedStatement(
1233 SQL_FROM_HERE, "DELETE FROM cookies WHERE host_key=? AND secure=?"));
1234 if (!del_smt.is_valid()) {
1235 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1236 return;
1237 }
1238
1239 sql::Transaction transaction(db_.get());
1240 if (!transaction.Begin()) {
1241 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1242 return;
1243 }
1244
1245 for (CookiesPerOriginMap::iterator it = cookies_per_origin_.begin();
1246 it != cookies_per_origin_.end(); ++it) {
1247 if (it->second <= 0) {
1248 DCHECK_EQ(0, it->second);
1249 continue;
1250 }
1251 const GURL url(net::cookie_util::CookieOriginToURL(it->first.first,
1252 it->first.second));
1253 if (!url.is_valid() || !special_storage_policy_->IsStorageSessionOnly(url))
1254 continue;
1255
1256 del_smt.Reset(true);
1257 del_smt.BindString(0, it->first.first);
1258 del_smt.BindInt(1, it->first.second);
1259 if (!del_smt.Run())
1260 NOTREACHED() << "Could not delete a cookie from the DB.";
1261 }
1262
1263 if (!transaction.Commit())
1264 LOG(WARNING) << "Unable to delete cookies on shutdown.";
1265 }
1266
1267 void SQLitePersistentCookieStore::Backend::DatabaseErrorCallback(
1268 int error,
1269 sql::Statement* stmt) {
1270 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1271
1272 if (!sql::IsErrorCatastrophic(error))
1273 return;
1274
1275 // TODO(shess): Running KillDatabase() multiple times should be
1276 // safe.
1277 if (corruption_detected_)
1278 return;
1279
1280 corruption_detected_ = true;
1281
1282 // Don't just do the close/delete here, as we are being called by |db| and
1283 // that seems dangerous.
1284 // TODO(shess): Consider just calling RazeAndClose() immediately.
1285 // db_ may not be safe to reset at this point, but RazeAndClose()
1286 // would cause the stack to unwind safely with errors.
1287 PostBackgroundTask(FROM_HERE, base::Bind(&Backend::KillDatabase, this));
1288 }
1289
1290 void SQLitePersistentCookieStore::Backend::KillDatabase() {
1291 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1292
1293 if (db_) {
1294 // This Backend will now be in-memory only. In a future run we will recreate
1295 // the database. Hopefully things go better then!
1296 bool success = db_->RazeAndClose();
1297 UMA_HISTOGRAM_BOOLEAN("Cookie.KillDatabaseResult", success);
1298 meta_table_.Reset();
1299 db_.reset();
1300 }
1301 }
1302
1303 void SQLitePersistentCookieStore::Backend::SetForceKeepSessionState() {
1304 base::AutoLock locked(lock_);
1305 force_keep_session_state_ = true;
1306 }
1307
1308 void SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup() {
1309 DCHECK(background_task_runner_->RunsTasksOnCurrentThread());
1310 if (!db_->Execute("DELETE FROM cookies WHERE persistent != 1"))
1311 LOG(WARNING) << "Unable to delete session cookies.";
1312 }
1313
1314 void SQLitePersistentCookieStore::Backend::PostBackgroundTask(
1315 const tracked_objects::Location& origin, const base::Closure& task) {
1316 if (!background_task_runner_->PostTask(origin, task)) {
1317 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1318 << " to background_task_runner_.";
1319 }
1320 }
1321
1322 void SQLitePersistentCookieStore::Backend::PostClientTask(
1323 const tracked_objects::Location& origin, const base::Closure& task) {
1324 if (!client_task_runner_->PostTask(origin, task)) {
1325 LOG(WARNING) << "Failed to post task from " << origin.ToString()
1326 << " to client_task_runner_.";
1327 }
1328 }
1329
1330 void SQLitePersistentCookieStore::Backend::FinishedLoadingCookies(
1331 const LoadedCallback& loaded_callback,
1332 bool success) {
1333 PostClientTask(FROM_HERE, base::Bind(&Backend::CompleteLoadInForeground, this,
1334 loaded_callback, success));
1335 }
1336
1337 SQLitePersistentCookieStore::SQLitePersistentCookieStore(
1338 const base::FilePath& path,
1339 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner,
1340 const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
1341 bool restore_old_session_cookies,
1342 storage::SpecialStoragePolicy* special_storage_policy,
1343 net::CookieCryptoDelegate* crypto_delegate)
1344 : backend_(new Backend(path,
1345 client_task_runner,
1346 background_task_runner,
1347 restore_old_session_cookies,
1348 special_storage_policy,
1349 crypto_delegate)) {
1350 }
1351
1352 void SQLitePersistentCookieStore::Load(const LoadedCallback& loaded_callback) {
1353 backend_->Load(loaded_callback);
1354 }
1355
1356 void SQLitePersistentCookieStore::LoadCookiesForKey(
1357 const std::string& key,
1358 const LoadedCallback& loaded_callback) {
1359 backend_->LoadCookiesForKey(key, loaded_callback);
1360 }
1361
1362 void SQLitePersistentCookieStore::AddCookie(const net::CanonicalCookie& cc) {
1363 backend_->AddCookie(cc);
1364 }
1365
1366 void SQLitePersistentCookieStore::UpdateCookieAccessTime(
1367 const net::CanonicalCookie& cc) {
1368 backend_->UpdateCookieAccessTime(cc);
1369 }
1370
1371 void SQLitePersistentCookieStore::DeleteCookie(const net::CanonicalCookie& cc) {
1372 backend_->DeleteCookie(cc);
1373 }
1374
1375 void SQLitePersistentCookieStore::SetForceKeepSessionState() {
1376 backend_->SetForceKeepSessionState();
1377 }
1378
1379 void SQLitePersistentCookieStore::Flush(const base::Closure& callback) {
1380 backend_->Flush(callback);
1381 }
1382
1383 SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
1384 backend_->Close();
1385 // We release our reference to the Backend, though it will probably still have
1386 // a reference if the background runner has not run Close() yet.
1387 }
1388
1389 CookieStoreConfig::CookieStoreConfig()
1390 : session_cookie_mode(EPHEMERAL_SESSION_COOKIES),
1391 crypto_delegate(NULL) {
1392 // Default to an in-memory cookie store.
1393 }
1394
1395 CookieStoreConfig::CookieStoreConfig(
1396 const base::FilePath& path,
1397 SessionCookieMode session_cookie_mode,
1398 storage::SpecialStoragePolicy* storage_policy,
1399 net::CookieMonsterDelegate* cookie_delegate)
1400 : path(path),
1401 session_cookie_mode(session_cookie_mode),
1402 storage_policy(storage_policy),
1403 cookie_delegate(cookie_delegate),
1404 crypto_delegate(NULL) {
1405 CHECK(!path.empty() || session_cookie_mode == EPHEMERAL_SESSION_COOKIES);
1406 }
1407
1408 CookieStoreConfig::~CookieStoreConfig() {
1409 }
1410
1411 net::CookieStore* CreateCookieStore(const CookieStoreConfig& config) {
1412 // TODO(bcwhite): Remove ScopedTracker below once crbug.com/483686 is fixed.
1413 tracked_objects::ScopedTracker tracking_profile(
1414 FROM_HERE_WITH_EXPLICIT_FUNCTION("483686 content::CreateCookieStore"));
1415
1416 net::CookieMonster* cookie_monster = NULL;
1417
1418 if (config.path.empty()) {
1419 // Empty path means in-memory store.
1420 cookie_monster = new net::CookieMonster(NULL, config.cookie_delegate.get());
1421 } else {
1422 scoped_refptr<base::SequencedTaskRunner> client_task_runner =
1423 config.client_task_runner;
1424 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
1425 config.background_task_runner;
1426
1427 if (!client_task_runner.get()) {
1428 client_task_runner =
1429 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
1430 }
1431
1432 if (!background_task_runner.get()) {
1433 background_task_runner =
1434 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
1435 BrowserThread::GetBlockingPool()->GetSequenceToken());
1436 }
1437
1438 SQLitePersistentCookieStore* persistent_store =
1439 new SQLitePersistentCookieStore(
1440 config.path,
1441 client_task_runner,
1442 background_task_runner,
1443 (config.session_cookie_mode ==
1444 CookieStoreConfig::RESTORED_SESSION_COOKIES),
1445 config.storage_policy.get(),
1446 config.crypto_delegate);
1447
1448 cookie_monster =
1449 new net::CookieMonster(persistent_store, config.cookie_delegate.get());
1450 if ((config.session_cookie_mode ==
1451 CookieStoreConfig::PERSISTANT_SESSION_COOKIES) ||
1452 (config.session_cookie_mode ==
1453 CookieStoreConfig::RESTORED_SESSION_COOKIES)) {
1454 cookie_monster->SetPersistSessionCookies(true);
1455 }
1456 }
1457
1458 return cookie_monster;
1459 }
1460
1461 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698