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