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

Side by Side Diff: net/cookies/cookie_monster.cc

Issue 1698693002: Make CookieStore no longer threadsafe. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@getcookiemonster
Patch Set: response to comments Created 4 years, 9 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
« no previous file with comments | « net/cookies/cookie_monster.h ('k') | net/cookies/cookie_monster_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // Portions of this code based on Mozilla: 5 // Portions of this code based on Mozilla:
6 // (netwerk/cookie/src/nsCookieService.cpp) 6 // (netwerk/cookie/src/nsCookieService.cpp)
7 /* ***** BEGIN LICENSE BLOCK ***** 7 /* ***** BEGIN LICENSE BLOCK *****
8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1 8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
9 * 9 *
10 * The contents of this file are subject to the Mozilla Public License Version 10 * The contents of this file are subject to the Mozilla Public License Version
(...skipping 326 matching lines...) Expand 10 before | Expand all | Expand 10 after
337 int last_access_threshold_milliseconds) 337 int last_access_threshold_milliseconds)
338 : initialized_(false), 338 : initialized_(false),
339 started_fetching_all_cookies_(false), 339 started_fetching_all_cookies_(false),
340 finished_fetching_all_cookies_(false), 340 finished_fetching_all_cookies_(false),
341 fetch_strategy_(kUnknownFetch), 341 fetch_strategy_(kUnknownFetch),
342 store_(store), 342 store_(store),
343 last_access_threshold_(base::TimeDelta::FromMilliseconds( 343 last_access_threshold_(base::TimeDelta::FromMilliseconds(
344 last_access_threshold_milliseconds)), 344 last_access_threshold_milliseconds)),
345 delegate_(delegate), 345 delegate_(delegate),
346 last_statistic_record_time_(base::Time::Now()), 346 last_statistic_record_time_(base::Time::Now()),
347 persist_session_cookies_(false) { 347 persist_session_cookies_(false),
348 weak_ptr_factory_(this) {
348 InitializeHistograms(); 349 InitializeHistograms();
349 cookieable_schemes_.insert( 350 cookieable_schemes_.insert(
350 cookieable_schemes_.begin(), kDefaultCookieableSchemes, 351 cookieable_schemes_.begin(), kDefaultCookieableSchemes,
351 kDefaultCookieableSchemes + kDefaultCookieableSchemesCount); 352 kDefaultCookieableSchemes + kDefaultCookieableSchemesCount);
352 } 353 }
353 354
354 // Task classes for queueing the coming request. 355 // Task classes for queueing the coming request.
355 356
356 class CookieMonster::CookieMonsterTask 357 class CookieMonster::CookieMonsterTask
357 : public base::RefCountedThreadSafe<CookieMonsterTask> { 358 : public base::RefCountedThreadSafe<CookieMonsterTask> {
358 public: 359 public:
359 // Runs the task and invokes the client callback on the thread that 360 // Runs the task and invokes the client callback on the thread that
360 // originally constructed the task. 361 // originally constructed the task.
361 virtual void Run() = 0; 362 virtual void Run() = 0;
362 363
363 protected: 364 protected:
364 explicit CookieMonsterTask(CookieMonster* cookie_monster); 365 explicit CookieMonsterTask(CookieMonster* cookie_monster);
365 virtual ~CookieMonsterTask(); 366 virtual ~CookieMonsterTask();
366 367
367 // Invokes the callback immediately, if the current thread is the one
368 // that originated the task, or queues the callback for execution on the
369 // appropriate thread. Maintains a reference to this CookieMonsterTask
370 // instance until the callback completes.
371 void InvokeCallback(base::Closure callback);
372
373 CookieMonster* cookie_monster() { return cookie_monster_; } 368 CookieMonster* cookie_monster() { return cookie_monster_; }
374 369
375 private: 370 private:
376 friend class base::RefCountedThreadSafe<CookieMonsterTask>; 371 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
377 372
378 CookieMonster* cookie_monster_; 373 CookieMonster* cookie_monster_;
379 scoped_refptr<base::SingleThreadTaskRunner> thread_;
380 374
381 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask); 375 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
382 }; 376 };
383 377
384 CookieMonster::CookieMonsterTask::CookieMonsterTask( 378 CookieMonster::CookieMonsterTask::CookieMonsterTask(
385 CookieMonster* cookie_monster) 379 CookieMonster* cookie_monster)
386 : cookie_monster_(cookie_monster), 380 : cookie_monster_(cookie_monster) {}
387 thread_(base::ThreadTaskRunnerHandle::Get()) {
388 }
389 381
390 CookieMonster::CookieMonsterTask::~CookieMonsterTask() { 382 CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
391 } 383 }
392 384
393 // Unfortunately, one cannot re-bind a Callback with parameters into a closure.
394 // Therefore, the closure passed to InvokeCallback is a clumsy binding of
395 // Callback::Run on a wrapped Callback instance. Since Callback is not
396 // reference counted, we bind to an instance that is a member of the
397 // CookieMonsterTask subclass. Then, we cannot simply post the callback to a
398 // message loop because the underlying instance may be destroyed (along with the
399 // CookieMonsterTask instance) in the interim. Therefore, we post a callback
400 // bound to the CookieMonsterTask, which *is* reference counted (thus preventing
401 // destruction of the original callback), and which invokes the closure (which
402 // invokes the original callback with the returned data).
403 void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback) {
404 if (thread_->BelongsToCurrentThread()) {
405 callback.Run();
406 } else {
407 thread_->PostTask(FROM_HERE, base::Bind(&CookieMonsterTask::InvokeCallback,
408 this, callback));
409 }
410 }
411
412 // Task class for SetCookieWithDetails call. 385 // Task class for SetCookieWithDetails call.
413 class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask { 386 class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
414 public: 387 public:
415 SetCookieWithDetailsTask(CookieMonster* cookie_monster, 388 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
416 const GURL& url, 389 const GURL& url,
417 const std::string& name, 390 const std::string& name,
418 const std::string& value, 391 const std::string& value,
419 const std::string& domain, 392 const std::string& domain,
420 const std::string& path, 393 const std::string& path,
421 base::Time creation_time, 394 base::Time creation_time,
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
466 SetCookiesCallback callback_; 439 SetCookiesCallback callback_;
467 440
468 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask); 441 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
469 }; 442 };
470 443
471 void CookieMonster::SetCookieWithDetailsTask::Run() { 444 void CookieMonster::SetCookieWithDetailsTask::Run() {
472 bool success = this->cookie_monster()->SetCookieWithDetails( 445 bool success = this->cookie_monster()->SetCookieWithDetails(
473 url_, name_, value_, domain_, path_, creation_time_, expiration_time_, 446 url_, name_, value_, domain_, path_, creation_time_, expiration_time_,
474 last_access_time_, secure_, http_only_, same_site_, 447 last_access_time_, secure_, http_only_, same_site_,
475 enforce_strict_secure_, priority_); 448 enforce_strict_secure_, priority_);
476 if (!callback_.is_null()) { 449 if (!callback_.is_null())
477 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run, 450 callback_.Run(success);
478 base::Unretained(&callback_), success));
479 }
480 } 451 }
481 452
482 // Task class for GetAllCookies call. 453 // Task class for GetAllCookies call.
483 class CookieMonster::GetAllCookiesTask : public CookieMonsterTask { 454 class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
484 public: 455 public:
485 GetAllCookiesTask(CookieMonster* cookie_monster, 456 GetAllCookiesTask(CookieMonster* cookie_monster,
486 const GetCookieListCallback& callback) 457 const GetCookieListCallback& callback)
487 : CookieMonsterTask(cookie_monster), callback_(callback) {} 458 : CookieMonsterTask(cookie_monster), callback_(callback) {}
488 459
489 // CookieMonsterTask 460 // CookieMonsterTask
490 void Run() override; 461 void Run() override;
491 462
492 protected: 463 protected:
493 ~GetAllCookiesTask() override {} 464 ~GetAllCookiesTask() override {}
494 465
495 private: 466 private:
496 GetCookieListCallback callback_; 467 GetCookieListCallback callback_;
497 468
498 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask); 469 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
499 }; 470 };
500 471
501 void CookieMonster::GetAllCookiesTask::Run() { 472 void CookieMonster::GetAllCookiesTask::Run() {
502 if (!callback_.is_null()) { 473 if (!callback_.is_null()) {
503 CookieList cookies = this->cookie_monster()->GetAllCookies(); 474 CookieList cookies = this->cookie_monster()->GetAllCookies();
504 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run, 475 callback_.Run(cookies);
505 base::Unretained(&callback_), cookies));
506 } 476 }
507 } 477 }
508 478
509 // Task class for GetCookieListWithOptionsAsync call. 479 // Task class for GetCookieListWithOptionsAsync call.
510 class CookieMonster::GetCookieListWithOptionsTask : public CookieMonsterTask { 480 class CookieMonster::GetCookieListWithOptionsTask : public CookieMonsterTask {
511 public: 481 public:
512 GetCookieListWithOptionsTask(CookieMonster* cookie_monster, 482 GetCookieListWithOptionsTask(CookieMonster* cookie_monster,
513 const GURL& url, 483 const GURL& url,
514 const CookieOptions& options, 484 const CookieOptions& options,
515 const GetCookieListCallback& callback) 485 const GetCookieListCallback& callback)
(...skipping 13 matching lines...) Expand all
529 CookieOptions options_; 499 CookieOptions options_;
530 GetCookieListCallback callback_; 500 GetCookieListCallback callback_;
531 501
532 DISALLOW_COPY_AND_ASSIGN(GetCookieListWithOptionsTask); 502 DISALLOW_COPY_AND_ASSIGN(GetCookieListWithOptionsTask);
533 }; 503 };
534 504
535 void CookieMonster::GetCookieListWithOptionsTask::Run() { 505 void CookieMonster::GetCookieListWithOptionsTask::Run() {
536 if (!callback_.is_null()) { 506 if (!callback_.is_null()) {
537 CookieList cookies = 507 CookieList cookies =
538 this->cookie_monster()->GetCookieListWithOptions(url_, options_); 508 this->cookie_monster()->GetCookieListWithOptions(url_, options_);
539 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run, 509 callback_.Run(cookies);
540 base::Unretained(&callback_), cookies));
541 } 510 }
542 } 511 }
543 512
544 template <typename Result> 513 template <typename Result>
545 struct CallbackType { 514 struct CallbackType {
546 typedef base::Callback<void(Result)> Type; 515 typedef base::Callback<void(Result)> Type;
547 }; 516 };
548 517
549 template <> 518 template <>
550 struct CallbackType<void> { 519 struct CallbackType<void> {
(...skipping 10 matching lines...) Expand all
561 530
562 // CookieMonsterTask: 531 // CookieMonsterTask:
563 void Run() override; 532 void Run() override;
564 533
565 protected: 534 protected:
566 ~DeleteTask() override; 535 ~DeleteTask() override;
567 536
568 private: 537 private:
569 // Runs the delete task and returns a result. 538 // Runs the delete task and returns a result.
570 virtual Result RunDeleteTask() = 0; 539 virtual Result RunDeleteTask() = 0;
540 // Runs the delete task and then returns a callback to be called after
541 // flushing the persistent store.
542 // TODO(mmenke): This seems like a pretty ugly and needlessly confusing API.
543 // Simplify it?
571 base::Closure RunDeleteTaskAndBindCallback(); 544 base::Closure RunDeleteTaskAndBindCallback();
572 void FlushDone(const base::Closure& callback);
573 545
574 typename CallbackType<Result>::Type callback_; 546 typename CallbackType<Result>::Type callback_;
575 547
576 DISALLOW_COPY_AND_ASSIGN(DeleteTask); 548 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
577 }; 549 };
578 550
579 template <typename Result> 551 template <typename Result>
580 CookieMonster::DeleteTask<Result>::~DeleteTask() { 552 CookieMonster::DeleteTask<Result>::~DeleteTask() {
581 } 553 }
582 554
583 template <typename Result> 555 template <typename Result>
584 base::Closure 556 base::Closure
585 CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() { 557 CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() {
586 Result result = RunDeleteTask(); 558 Result result = RunDeleteTask();
587 if (callback_.is_null()) 559 if (callback_.is_null())
588 return base::Closure(); 560 return base::Closure();
589 return base::Bind(callback_, result); 561 return base::Bind(callback_, result);
590 } 562 }
591 563
592 template <> 564 template <>
593 base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() { 565 base::Closure CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
594 RunDeleteTask(); 566 RunDeleteTask();
595 return callback_; 567 return callback_;
596 } 568 }
597 569
598 template <typename Result> 570 template <typename Result>
599 void CookieMonster::DeleteTask<Result>::Run() { 571 void CookieMonster::DeleteTask<Result>::Run() {
600 this->cookie_monster()->FlushStore(base::Bind( 572 base::Closure callback = RunDeleteTaskAndBindCallback();
601 &DeleteTask<Result>::FlushDone, this, RunDeleteTaskAndBindCallback()));
602 }
603
604 template <typename Result>
605 void CookieMonster::DeleteTask<Result>::FlushDone(
606 const base::Closure& callback) {
607 if (!callback.is_null()) { 573 if (!callback.is_null()) {
608 this->InvokeCallback(callback); 574 callback = base::Bind(
575 &CookieMonster::RunCallback,
576 this->cookie_monster()->weak_ptr_factory_.GetWeakPtr(), callback);
609 } 577 }
578 this->cookie_monster()->FlushStore(callback);
610 } 579 }
611 580
612 // Task class for DeleteAllCreatedBetween call. 581 // Task class for DeleteAllCreatedBetween call.
613 class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> { 582 class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<int> {
614 public: 583 public:
615 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster, 584 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
616 const Time& delete_begin, 585 const Time& delete_begin,
617 const Time& delete_end, 586 const Time& delete_end,
618 const DeleteCallback& callback) 587 const DeleteCallback& callback)
619 : DeleteTask<int>(cookie_monster, callback), 588 : DeleteTask<int>(cookie_monster, callback),
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after
720 std::string cookie_line_; 689 std::string cookie_line_;
721 CookieOptions options_; 690 CookieOptions options_;
722 SetCookiesCallback callback_; 691 SetCookiesCallback callback_;
723 692
724 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask); 693 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
725 }; 694 };
726 695
727 void CookieMonster::SetCookieWithOptionsTask::Run() { 696 void CookieMonster::SetCookieWithOptionsTask::Run() {
728 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_, 697 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_,
729 options_); 698 options_);
730 if (!callback_.is_null()) { 699 if (!callback_.is_null())
731 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run, 700 callback_.Run(result);
732 base::Unretained(&callback_), result));
733 }
734 } 701 }
735 702
736 // Task class for SetAllCookies call. 703 // Task class for SetAllCookies call.
737 class CookieMonster::SetAllCookiesTask : public CookieMonsterTask { 704 class CookieMonster::SetAllCookiesTask : public CookieMonsterTask {
738 public: 705 public:
739 SetAllCookiesTask(CookieMonster* cookie_monster, 706 SetAllCookiesTask(CookieMonster* cookie_monster,
740 const CookieList& list, 707 const CookieList& list,
741 const SetCookiesCallback& callback) 708 const SetCookiesCallback& callback)
742 : CookieMonsterTask(cookie_monster), list_(list), callback_(callback) {} 709 : CookieMonsterTask(cookie_monster), list_(list), callback_(callback) {}
743 710
(...skipping 19 matching lines...) Expand all
763 730
764 for (CookieList::const_iterator it = negative_diff.begin(); 731 for (CookieList::const_iterator it = negative_diff.begin();
765 it != negative_diff.end(); ++it) { 732 it != negative_diff.end(); ++it) {
766 this->cookie_monster()->DeleteCanonicalCookie(*it); 733 this->cookie_monster()->DeleteCanonicalCookie(*it);
767 } 734 }
768 735
769 bool result = true; 736 bool result = true;
770 if (positive_diff.size() > 0) 737 if (positive_diff.size() > 0)
771 result = this->cookie_monster()->SetCanonicalCookies(list_); 738 result = this->cookie_monster()->SetCanonicalCookies(list_);
772 739
773 if (!callback_.is_null()) { 740 if (!callback_.is_null())
774 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run, 741 callback_.Run(result);
775 base::Unretained(&callback_), result));
776 }
777 } 742 }
778 743
779 // Task class for GetCookiesWithOptions call. 744 // Task class for GetCookiesWithOptions call.
780 class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask { 745 class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
781 public: 746 public:
782 GetCookiesWithOptionsTask(CookieMonster* cookie_monster, 747 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
783 const GURL& url, 748 const GURL& url,
784 const CookieOptions& options, 749 const CookieOptions& options,
785 const GetCookiesCallback& callback) 750 const GetCookiesCallback& callback)
786 : CookieMonsterTask(cookie_monster), 751 : CookieMonsterTask(cookie_monster),
(...skipping 15 matching lines...) Expand all
802 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask); 767 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
803 }; 768 };
804 769
805 void CookieMonster::GetCookiesWithOptionsTask::Run() { 770 void CookieMonster::GetCookiesWithOptionsTask::Run() {
806 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed. 771 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
807 tracked_objects::ScopedTracker tracking_profile( 772 tracked_objects::ScopedTracker tracking_profile(
808 FROM_HERE_WITH_EXPLICIT_FUNCTION( 773 FROM_HERE_WITH_EXPLICIT_FUNCTION(
809 "456373 CookieMonster::GetCookiesWithOptionsTask::Run")); 774 "456373 CookieMonster::GetCookiesWithOptionsTask::Run"));
810 std::string cookie = 775 std::string cookie =
811 this->cookie_monster()->GetCookiesWithOptions(url_, options_); 776 this->cookie_monster()->GetCookiesWithOptions(url_, options_);
812 if (!callback_.is_null()) { 777 if (!callback_.is_null())
813 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run, 778 callback_.Run(cookie);
814 base::Unretained(&callback_), cookie));
815 }
816 } 779 }
817 780
818 // Task class for DeleteCookie call. 781 // Task class for DeleteCookie call.
819 class CookieMonster::DeleteCookieTask : public DeleteTask<void> { 782 class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
820 public: 783 public:
821 DeleteCookieTask(CookieMonster* cookie_monster, 784 DeleteCookieTask(CookieMonster* cookie_monster,
822 const GURL& url, 785 const GURL& url,
823 const std::string& cookie_name, 786 const std::string& cookie_name,
824 const base::Closure& callback) 787 const base::Closure& callback)
825 : DeleteTask<void>(cookie_monster, callback), 788 : DeleteTask<void>(cookie_monster, callback),
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
882 CookiePriority priority, 845 CookiePriority priority,
883 const SetCookiesCallback& callback) { 846 const SetCookiesCallback& callback) {
884 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask( 847 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask(
885 this, url, name, value, domain, path, creation_time, expiration_time, 848 this, url, name, value, domain, path, creation_time, expiration_time,
886 last_access_time, secure, http_only, same_site, enforce_strict_secure, 849 last_access_time, secure, http_only, same_site, enforce_strict_secure,
887 priority, callback); 850 priority, callback);
888 DoCookieTaskForURL(task, url); 851 DoCookieTaskForURL(task, url);
889 } 852 }
890 853
891 void CookieMonster::FlushStore(const base::Closure& callback) { 854 void CookieMonster::FlushStore(const base::Closure& callback) {
892 base::AutoLock autolock(lock_); 855 DCHECK(thread_checker_.CalledOnValidThread());
893 if (initialized_ && store_.get()) 856 if (initialized_ && store_.get())
894 store_->Flush(callback); 857 store_->Flush(callback);
895 else if (!callback.is_null()) 858 else if (!callback.is_null())
896 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); 859 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback);
897 } 860 }
898 861
899 void CookieMonster::SetForceKeepSessionState() { 862 void CookieMonster::SetForceKeepSessionState() {
863 DCHECK(thread_checker_.CalledOnValidThread());
900 if (store_) 864 if (store_)
901 store_->SetForceKeepSessionState(); 865 store_->SetForceKeepSessionState();
902 } 866 }
903 867
904 void CookieMonster::SetAllCookiesAsync(const CookieList& list, 868 void CookieMonster::SetAllCookiesAsync(const CookieList& list,
905 const SetCookiesCallback& callback) { 869 const SetCookiesCallback& callback) {
906 scoped_refptr<SetAllCookiesTask> task = 870 scoped_refptr<SetAllCookiesTask> task =
907 new SetAllCookiesTask(this, list, callback); 871 new SetAllCookiesTask(this, list, callback);
908 DoCookieTask(task); 872 DoCookieTask(task);
909 } 873 }
(...skipping 77 matching lines...) Expand 10 before | Expand all | Expand 10 after
987 void CookieMonster::DeleteSessionCookiesAsync( 951 void CookieMonster::DeleteSessionCookiesAsync(
988 const CookieStore::DeleteCallback& callback) { 952 const CookieStore::DeleteCallback& callback) {
989 scoped_refptr<DeleteSessionCookiesTask> task = 953 scoped_refptr<DeleteSessionCookiesTask> task =
990 new DeleteSessionCookiesTask(this, callback); 954 new DeleteSessionCookiesTask(this, callback);
991 955
992 DoCookieTask(task); 956 DoCookieTask(task);
993 } 957 }
994 958
995 void CookieMonster::SetCookieableSchemes( 959 void CookieMonster::SetCookieableSchemes(
996 const std::vector<std::string>& schemes) { 960 const std::vector<std::string>& schemes) {
997 base::AutoLock autolock(lock_); 961 DCHECK(thread_checker_.CalledOnValidThread());
998 962
999 // Calls to this method will have no effect if made after a WebView or 963 // Calls to this method will have no effect if made after a WebView or
1000 // CookieManager instance has been created. 964 // CookieManager instance has been created.
1001 if (initialized_) 965 if (initialized_)
1002 return; 966 return;
1003 967
1004 cookieable_schemes_ = schemes; 968 cookieable_schemes_ = schemes;
1005 } 969 }
1006 970
1007 // This function must be called before the CookieMonster is used. 971 // This function must be called before the CookieMonster is used.
1008 void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) { 972 void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
973 DCHECK(thread_checker_.CalledOnValidThread());
1009 DCHECK(!initialized_); 974 DCHECK(!initialized_);
1010 persist_session_cookies_ = persist_session_cookies; 975 persist_session_cookies_ = persist_session_cookies;
1011 } 976 }
1012 977
1013 bool CookieMonster::IsCookieableScheme(const std::string& scheme) { 978 bool CookieMonster::IsCookieableScheme(const std::string& scheme) {
1014 base::AutoLock autolock(lock_); 979 DCHECK(thread_checker_.CalledOnValidThread());
1015 980
1016 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(), 981 return std::find(cookieable_schemes_.begin(), cookieable_schemes_.end(),
1017 scheme) != cookieable_schemes_.end(); 982 scheme) != cookieable_schemes_.end();
1018 } 983 }
1019 984
1020 const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http", "https", 985 const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http", "https",
1021 "ws", "wss"}; 986 "ws", "wss"};
1022 const int CookieMonster::kDefaultCookieableSchemesCount = 987 const int CookieMonster::kDefaultCookieableSchemesCount =
1023 arraysize(kDefaultCookieableSchemes); 988 arraysize(kDefaultCookieableSchemes);
1024 989
1025 scoped_ptr<CookieStore::CookieChangedSubscription> 990 scoped_ptr<CookieStore::CookieChangedSubscription>
1026 CookieMonster::AddCallbackForCookie(const GURL& gurl, 991 CookieMonster::AddCallbackForCookie(const GURL& gurl,
1027 const std::string& name, 992 const std::string& name,
1028 const CookieChangedCallback& callback) { 993 const CookieChangedCallback& callback) {
1029 base::AutoLock autolock(lock_); 994 DCHECK(thread_checker_.CalledOnValidThread());
1030 std::pair<GURL, std::string> key(gurl, name); 995 std::pair<GURL, std::string> key(gurl, name);
1031 if (hook_map_.count(key) == 0) 996 if (hook_map_.count(key) == 0)
1032 hook_map_[key] = make_linked_ptr(new CookieChangedCallbackList()); 997 hook_map_[key] = make_linked_ptr(new CookieChangedCallbackList());
1033 return hook_map_[key]->Add( 998 return hook_map_[key]->Add(
1034 base::Bind(&RunAsync, base::ThreadTaskRunnerHandle::Get(), callback)); 999 base::Bind(&RunAsync, base::ThreadTaskRunnerHandle::Get(), callback));
1035 } 1000 }
1036 1001
1037 CookieMonster::~CookieMonster() { 1002 CookieMonster::~CookieMonster() {
1038 // Clean up cookies 1003 DCHECK(thread_checker_.CalledOnValidThread());
1039 1004
1040 // InternalDeleteCookie expects the lock to be held, even though there can be
1041 // no contention here.
1042 base::AutoLock autolock(lock_);
1043 for (CookieMap::iterator cookie_it = cookies_.begin(); 1005 for (CookieMap::iterator cookie_it = cookies_.begin();
1044 cookie_it != cookies_.end();) { 1006 cookie_it != cookies_.end();) {
1045 CookieMap::iterator current_cookie_it = cookie_it; 1007 CookieMap::iterator current_cookie_it = cookie_it;
1046 ++cookie_it; 1008 ++cookie_it;
1047 InternalDeleteCookie(current_cookie_it, false /* sync_to_store */, 1009 InternalDeleteCookie(current_cookie_it, false /* sync_to_store */,
1048 DELETE_COOKIE_DONT_RECORD); 1010 DELETE_COOKIE_DONT_RECORD);
1049 } 1011 }
1050 } 1012 }
1051 1013
1052 bool CookieMonster::SetCookieWithDetails(const GURL& url, 1014 bool CookieMonster::SetCookieWithDetails(const GURL& url,
1053 const std::string& name, 1015 const std::string& name,
1054 const std::string& value, 1016 const std::string& value,
1055 const std::string& domain, 1017 const std::string& domain,
1056 const std::string& path, 1018 const std::string& path,
1057 base::Time creation_time, 1019 base::Time creation_time,
1058 base::Time expiration_time, 1020 base::Time expiration_time,
1059 base::Time last_access_time, 1021 base::Time last_access_time,
1060 bool secure, 1022 bool secure,
1061 bool http_only, 1023 bool http_only,
1062 bool same_site, 1024 bool same_site,
1063 bool enforce_strict_secure, 1025 bool enforce_strict_secure,
1064 CookiePriority priority) { 1026 CookiePriority priority) {
1065 base::AutoLock autolock(lock_); 1027 DCHECK(thread_checker_.CalledOnValidThread());
1066 1028
1067 if (!HasCookieableScheme(url)) 1029 if (!HasCookieableScheme(url))
1068 return false; 1030 return false;
1069 1031
1070 // TODO(mmenke): This class assumes each cookie to have a unique creation 1032 // TODO(mmenke): This class assumes each cookie to have a unique creation
1071 // time. Allowing the caller to set the creation time violates that 1033 // time. Allowing the caller to set the creation time violates that
1072 // assumption. Worth fixing? Worth noting that time changes between browser 1034 // assumption. Worth fixing? Worth noting that time changes between browser
1073 // restarts can cause the same issue. 1035 // restarts can cause the same issue.
1074 base::Time actual_creation_time = creation_time; 1036 base::Time actual_creation_time = creation_time;
1075 if (creation_time.is_null()) { 1037 if (creation_time.is_null()) {
(...skipping 13 matching lines...) Expand all
1089 1051
1090 CookieOptions options; 1052 CookieOptions options;
1091 options.set_include_httponly(); 1053 options.set_include_httponly();
1092 options.set_include_same_site(); 1054 options.set_include_same_site();
1093 if (enforce_strict_secure) 1055 if (enforce_strict_secure)
1094 options.set_enforce_strict_secure(); 1056 options.set_enforce_strict_secure();
1095 return SetCanonicalCookie(std::move(cc), options); 1057 return SetCanonicalCookie(std::move(cc), options);
1096 } 1058 }
1097 1059
1098 CookieList CookieMonster::GetAllCookies() { 1060 CookieList CookieMonster::GetAllCookies() {
1099 base::AutoLock autolock(lock_); 1061 DCHECK(thread_checker_.CalledOnValidThread());
1100 1062
1101 // This function is being called to scrape the cookie list for management UI 1063 // This function is being called to scrape the cookie list for management UI
1102 // or similar. We shouldn't show expired cookies in this list since it will 1064 // or similar. We shouldn't show expired cookies in this list since it will
1103 // just be confusing to users, and this function is called rarely enough (and 1065 // just be confusing to users, and this function is called rarely enough (and
1104 // is already slow enough) that it's OK to take the time to garbage collect 1066 // is already slow enough) that it's OK to take the time to garbage collect
1105 // the expired cookies now. 1067 // the expired cookies now.
1106 // 1068 //
1107 // Note that this does not prune cookies to be below our limits (if we've 1069 // Note that this does not prune cookies to be below our limits (if we've
1108 // exceeded them) the way that calling GarbageCollect() would. 1070 // exceeded them) the way that calling GarbageCollect() would.
1109 GarbageCollectExpired( 1071 GarbageCollectExpired(
(...skipping 12 matching lines...) Expand all
1122 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin(); 1084 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1123 it != cookie_ptrs.end(); ++it) 1085 it != cookie_ptrs.end(); ++it)
1124 cookie_list.push_back(**it); 1086 cookie_list.push_back(**it);
1125 1087
1126 return cookie_list; 1088 return cookie_list;
1127 } 1089 }
1128 1090
1129 CookieList CookieMonster::GetCookieListWithOptions( 1091 CookieList CookieMonster::GetCookieListWithOptions(
1130 const GURL& url, 1092 const GURL& url,
1131 const CookieOptions& options) { 1093 const CookieOptions& options) {
1132 base::AutoLock autolock(lock_); 1094 DCHECK(thread_checker_.CalledOnValidThread());
1133 1095
1134 CookieList cookies; 1096 CookieList cookies;
1135 if (!HasCookieableScheme(url)) 1097 if (!HasCookieableScheme(url))
1136 return cookies; 1098 return cookies;
1137 1099
1138 std::vector<CanonicalCookie*> cookie_ptrs; 1100 std::vector<CanonicalCookie*> cookie_ptrs;
1139 FindCookiesForHostAndDomain(url, options, &cookie_ptrs); 1101 FindCookiesForHostAndDomain(url, options, &cookie_ptrs);
1140 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter); 1102 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1141 1103
1142 cookies.reserve(cookie_ptrs.size()); 1104 cookies.reserve(cookie_ptrs.size());
1143 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin(); 1105 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1144 it != cookie_ptrs.end(); it++) 1106 it != cookie_ptrs.end(); it++)
1145 cookies.push_back(**it); 1107 cookies.push_back(**it);
1146 1108
1147 return cookies; 1109 return cookies;
1148 } 1110 }
1149 1111
1150 int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin, 1112 int CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
1151 const Time& delete_end) { 1113 const Time& delete_end) {
1152 base::AutoLock autolock(lock_); 1114 DCHECK(thread_checker_.CalledOnValidThread());
1153 1115
1154 int num_deleted = 0; 1116 int num_deleted = 0;
1155 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 1117 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1156 CookieMap::iterator curit = it; 1118 CookieMap::iterator curit = it;
1157 CanonicalCookie* cc = curit->second; 1119 CanonicalCookie* cc = curit->second;
1158 ++it; 1120 ++it;
1159 1121
1160 if (cc->CreationDate() >= delete_begin && 1122 if (cc->CreationDate() >= delete_begin &&
1161 (delete_end.is_null() || cc->CreationDate() < delete_end)) { 1123 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
1162 InternalDeleteCookie(curit, true, /*sync_to_store*/ 1124 InternalDeleteCookie(curit, true, /*sync_to_store*/
1163 DELETE_COOKIE_EXPLICIT); 1125 DELETE_COOKIE_EXPLICIT);
1164 ++num_deleted; 1126 ++num_deleted;
1165 } 1127 }
1166 } 1128 }
1167 1129
1168 return num_deleted; 1130 return num_deleted;
1169 } 1131 }
1170 1132
1171 int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin, 1133 int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin,
1172 const Time delete_end, 1134 const Time delete_end,
1173 const GURL& url) { 1135 const GURL& url) {
1174 base::AutoLock autolock(lock_); 1136 DCHECK(thread_checker_.CalledOnValidThread());
1175 1137
1176 if (!HasCookieableScheme(url)) 1138 if (!HasCookieableScheme(url))
1177 return 0; 1139 return 0;
1178 1140
1179 const std::string host(url.host()); 1141 const std::string host(url.host());
1180 1142
1181 // We store host cookies in the store by their canonical host name; 1143 // We store host cookies in the store by their canonical host name;
1182 // domain cookies are stored with a leading ".". So this is a pretty 1144 // domain cookies are stored with a leading ".". So this is a pretty
1183 // simple lookup and per-cookie delete. 1145 // simple lookup and per-cookie delete.
1184 int num_deleted = 0; 1146 int num_deleted = 0;
(...skipping 15 matching lines...) Expand all
1200 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT); 1162 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1201 } 1163 }
1202 } 1164 }
1203 return num_deleted; 1165 return num_deleted;
1204 } 1166 }
1205 1167
1206 1168
1207 bool CookieMonster::SetCookieWithOptions(const GURL& url, 1169 bool CookieMonster::SetCookieWithOptions(const GURL& url,
1208 const std::string& cookie_line, 1170 const std::string& cookie_line,
1209 const CookieOptions& options) { 1171 const CookieOptions& options) {
1210 base::AutoLock autolock(lock_); 1172 DCHECK(thread_checker_.CalledOnValidThread());
1211 1173
1212 if (!HasCookieableScheme(url)) { 1174 if (!HasCookieableScheme(url)) {
1213 return false; 1175 return false;
1214 } 1176 }
1215 1177
1216 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options); 1178 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
1217 } 1179 }
1218 1180
1219 std::string CookieMonster::GetCookiesWithOptions(const GURL& url, 1181 std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
1220 const CookieOptions& options) { 1182 const CookieOptions& options) {
1221 base::AutoLock autolock(lock_); 1183 DCHECK(thread_checker_.CalledOnValidThread());
1222 1184
1223 if (!HasCookieableScheme(url)) 1185 if (!HasCookieableScheme(url))
1224 return std::string(); 1186 return std::string();
1225 1187
1226 std::vector<CanonicalCookie*> cookies; 1188 std::vector<CanonicalCookie*> cookies;
1227 FindCookiesForHostAndDomain(url, options, &cookies); 1189 FindCookiesForHostAndDomain(url, options, &cookies);
1228 std::sort(cookies.begin(), cookies.end(), CookieSorter); 1190 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1229 1191
1230 std::string cookie_line = BuildCookieLine(cookies); 1192 std::string cookie_line = BuildCookieLine(cookies);
1231 1193
1232 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line; 1194 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1233 1195
1234 return cookie_line; 1196 return cookie_line;
1235 } 1197 }
1236 1198
1237 void CookieMonster::DeleteCookie(const GURL& url, 1199 void CookieMonster::DeleteCookie(const GURL& url,
1238 const std::string& cookie_name) { 1200 const std::string& cookie_name) {
1239 base::AutoLock autolock(lock_); 1201 DCHECK(thread_checker_.CalledOnValidThread());
1240 1202
1241 if (!HasCookieableScheme(url)) 1203 if (!HasCookieableScheme(url))
1242 return; 1204 return;
1243 1205
1244 CookieOptions options; 1206 CookieOptions options;
1245 options.set_include_httponly(); 1207 options.set_include_httponly();
1246 options.set_include_same_site(); 1208 options.set_include_same_site();
1247 // Get the cookies for this host and its domain(s). 1209 // Get the cookies for this host and its domain(s).
1248 std::vector<CanonicalCookie*> cookies; 1210 std::vector<CanonicalCookie*> cookies;
1249 FindCookiesForHostAndDomain(url, options, &cookies); 1211 FindCookiesForHostAndDomain(url, options, &cookies);
(...skipping 11 matching lines...) Expand all
1261 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 1223 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1262 CookieMap::iterator curit = it; 1224 CookieMap::iterator curit = it;
1263 ++it; 1225 ++it;
1264 if (matching_cookies.find(curit->second) != matching_cookies.end()) { 1226 if (matching_cookies.find(curit->second) != matching_cookies.end()) {
1265 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT); 1227 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT);
1266 } 1228 }
1267 } 1229 }
1268 } 1230 }
1269 1231
1270 int CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) { 1232 int CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) {
1271 base::AutoLock autolock(lock_); 1233 DCHECK(thread_checker_.CalledOnValidThread());
1272 1234
1273 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain())); 1235 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1274 its.first != its.second; ++its.first) { 1236 its.first != its.second; ++its.first) {
1275 // The creation date acts as the unique index... 1237 // The creation date acts as the unique index...
1276 if (its.first->second->CreationDate() == cookie.CreationDate()) { 1238 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1277 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT); 1239 InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
1278 return 1; 1240 return 1;
1279 } 1241 }
1280 } 1242 }
1281 return 0; 1243 return 0;
1282 } 1244 }
1283 1245
1284 bool CookieMonster::SetCookieWithCreationTime(const GURL& url, 1246 bool CookieMonster::SetCookieWithCreationTime(const GURL& url,
1285 const std::string& cookie_line, 1247 const std::string& cookie_line,
1286 const base::Time& creation_time) { 1248 const base::Time& creation_time) {
1249 DCHECK(thread_checker_.CalledOnValidThread());
1287 DCHECK(!store_.get()) << "This method is only to be used by unit-tests."; 1250 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
1288 base::AutoLock autolock(lock_);
1289 1251
1290 if (!HasCookieableScheme(url)) { 1252 if (!HasCookieableScheme(url)) {
1291 return false; 1253 return false;
1292 } 1254 }
1293 1255
1294 MarkCookieStoreAsInitialized(); 1256 MarkCookieStoreAsInitialized();
1295 if (ShouldFetchAllCookiesWhenFetchingAnyCookie()) 1257 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1296 FetchAllCookiesIfNecessary(); 1258 FetchAllCookiesIfNecessary();
1297 1259
1298 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time, 1260 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time,
1299 CookieOptions()); 1261 CookieOptions());
1300 } 1262 }
1301 1263
1302 int CookieMonster::DeleteSessionCookies() { 1264 int CookieMonster::DeleteSessionCookies() {
1303 base::AutoLock autolock(lock_); 1265 DCHECK(thread_checker_.CalledOnValidThread());
1304 1266
1305 int num_deleted = 0; 1267 int num_deleted = 0;
1306 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 1268 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1307 CookieMap::iterator curit = it; 1269 CookieMap::iterator curit = it;
1308 CanonicalCookie* cc = curit->second; 1270 CanonicalCookie* cc = curit->second;
1309 ++it; 1271 ++it;
1310 1272
1311 if (!cc->IsPersistent()) { 1273 if (!cc->IsPersistent()) {
1312 InternalDeleteCookie(curit, true, /*sync_to_store*/ 1274 InternalDeleteCookie(curit, true, /*sync_to_store*/
1313 DELETE_COOKIE_EXPIRED); 1275 DELETE_COOKIE_EXPIRED);
1314 ++num_deleted; 1276 ++num_deleted;
1315 } 1277 }
1316 } 1278 }
1317 1279
1318 return num_deleted; 1280 return num_deleted;
1319 } 1281 }
1320 1282
1321 void CookieMonster::MarkCookieStoreAsInitialized() { 1283 void CookieMonster::MarkCookieStoreAsInitialized() {
1284 DCHECK(thread_checker_.CalledOnValidThread());
1322 initialized_ = true; 1285 initialized_ = true;
1323 } 1286 }
1324 1287
1325 void CookieMonster::FetchAllCookiesIfNecessary() { 1288 void CookieMonster::FetchAllCookiesIfNecessary() {
1289 DCHECK(thread_checker_.CalledOnValidThread());
1326 if (store_.get() && !started_fetching_all_cookies_) { 1290 if (store_.get() && !started_fetching_all_cookies_) {
1327 started_fetching_all_cookies_ = true; 1291 started_fetching_all_cookies_ = true;
1328 FetchAllCookies(); 1292 FetchAllCookies();
1329 } 1293 }
1330 } 1294 }
1331 1295
1332 void CookieMonster::FetchAllCookies() { 1296 void CookieMonster::FetchAllCookies() {
1297 DCHECK(thread_checker_.CalledOnValidThread());
1333 DCHECK(store_.get()) << "Store must exist to initialize"; 1298 DCHECK(store_.get()) << "Store must exist to initialize";
1334 DCHECK(!finished_fetching_all_cookies_) 1299 DCHECK(!finished_fetching_all_cookies_)
1335 << "All cookies have already been fetched."; 1300 << "All cookies have already been fetched.";
1336 1301
1337 // We bind in the current time so that we can report the wall-clock time for 1302 // We bind in the current time so that we can report the wall-clock time for
1338 // loading cookies. 1303 // loading cookies.
1339 store_->Load(base::Bind(&CookieMonster::OnLoaded, this, TimeTicks::Now())); 1304 store_->Load(base::Bind(&CookieMonster::OnLoaded,
1305 weak_ptr_factory_.GetWeakPtr(), TimeTicks::Now()));
1340 } 1306 }
1341 1307
1342 bool CookieMonster::ShouldFetchAllCookiesWhenFetchingAnyCookie() { 1308 bool CookieMonster::ShouldFetchAllCookiesWhenFetchingAnyCookie() {
1309 DCHECK(thread_checker_.CalledOnValidThread());
1310
1343 if (fetch_strategy_ == kUnknownFetch) { 1311 if (fetch_strategy_ == kUnknownFetch) {
1344 const std::string group_name = 1312 const std::string group_name =
1345 base::FieldTrialList::FindFullName(kCookieMonsterFetchStrategyName); 1313 base::FieldTrialList::FindFullName(kCookieMonsterFetchStrategyName);
1346 if (group_name == kFetchWhenNecessaryName) { 1314 if (group_name == kFetchWhenNecessaryName) {
1347 fetch_strategy_ = kFetchWhenNecessary; 1315 fetch_strategy_ = kFetchWhenNecessary;
1348 } else if (group_name == kAlwaysFetchName) { 1316 } else if (group_name == kAlwaysFetchName) {
1349 fetch_strategy_ = kAlwaysFetch; 1317 fetch_strategy_ = kAlwaysFetch;
1350 } else { 1318 } else {
1351 // The logic in the conditional is redundant, but it makes trials of 1319 // The logic in the conditional is redundant, but it makes trials of
1352 // the Finch experiment more explicit. 1320 // the Finch experiment more explicit.
1353 fetch_strategy_ = kAlwaysFetch; 1321 fetch_strategy_ = kAlwaysFetch;
1354 } 1322 }
1355 } 1323 }
1356 1324
1357 return fetch_strategy_ == kAlwaysFetch; 1325 return fetch_strategy_ == kAlwaysFetch;
1358 } 1326 }
1359 1327
1360 void CookieMonster::OnLoaded(TimeTicks beginning_time, 1328 void CookieMonster::OnLoaded(TimeTicks beginning_time,
1361 const std::vector<CanonicalCookie*>& cookies) { 1329 const std::vector<CanonicalCookie*>& cookies) {
1330 DCHECK(thread_checker_.CalledOnValidThread());
1362 StoreLoadedCookies(cookies); 1331 StoreLoadedCookies(cookies);
1363 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time); 1332 histogram_time_blocked_on_load_->AddTime(TimeTicks::Now() - beginning_time);
1364 1333
1365 // Invoke the task queue of cookie request. 1334 // Invoke the task queue of cookie request.
1366 InvokeQueue(); 1335 InvokeQueue();
1367 } 1336 }
1368 1337
1369 void CookieMonster::OnKeyLoaded(const std::string& key, 1338 void CookieMonster::OnKeyLoaded(const std::string& key,
1370 const std::vector<CanonicalCookie*>& cookies) { 1339 const std::vector<CanonicalCookie*>& cookies) {
1371 // This function does its own separate locking. 1340 DCHECK(thread_checker_.CalledOnValidThread());
1341
1372 StoreLoadedCookies(cookies); 1342 StoreLoadedCookies(cookies);
1373 1343
1374 std::deque<scoped_refptr<CookieMonsterTask>> tasks_pending_for_key; 1344 auto tasks_pending_for_key = tasks_pending_for_key_.find(key);
1375 1345
1376 // We need to do this repeatedly until no more tasks were added to the queue 1346 // TODO(mmenke): Can this be turned into a DCHECK?
1377 // during the period where we release the lock. 1347 if (tasks_pending_for_key == tasks_pending_for_key_.end())
1378 while (true) { 1348 return;
1379 {
1380 base::AutoLock autolock(lock_);
1381 std::map<std::string,
1382 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
1383 tasks_pending_for_key_.find(key);
1384 if (it == tasks_pending_for_key_.end()) {
1385 keys_loaded_.insert(key);
1386 return;
1387 }
1388 if (it->second.empty()) {
1389 keys_loaded_.insert(key);
1390 tasks_pending_for_key_.erase(it);
1391 return;
1392 }
1393 it->second.swap(tasks_pending_for_key);
1394 }
1395 1349
1396 while (!tasks_pending_for_key.empty()) { 1350 // Run all tasks for the key. Note that running a task can result in multiple
1397 scoped_refptr<CookieMonsterTask> task = tasks_pending_for_key.front(); 1351 // tasks being added to the back of the deque.
1398 task->Run(); 1352 while (!tasks_pending_for_key->second.empty()) {
1399 tasks_pending_for_key.pop_front(); 1353 scoped_refptr<CookieMonsterTask> task =
1400 } 1354 tasks_pending_for_key->second.front();
1355 tasks_pending_for_key->second.pop_front();
1356
1357 task->Run();
1401 } 1358 }
1359
1360 tasks_pending_for_key_.erase(tasks_pending_for_key);
1361
1362 // This has to be done last, in case running a task queues a new task for the
1363 // key, to ensure tasks are run in the correct order.
1364 keys_loaded_.insert(key);
1402 } 1365 }
1403 1366
1404 void CookieMonster::StoreLoadedCookies( 1367 void CookieMonster::StoreLoadedCookies(
1405 const std::vector<CanonicalCookie*>& cookies) { 1368 const std::vector<CanonicalCookie*>& cookies) {
1369 DCHECK(thread_checker_.CalledOnValidThread());
1370
1406 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is 1371 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is
1407 // fixed. 1372 // fixed.
1408 tracked_objects::ScopedTracker tracking_profile( 1373 tracked_objects::ScopedTracker tracking_profile(
1409 FROM_HERE_WITH_EXPLICIT_FUNCTION( 1374 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1410 "457528 CookieMonster::StoreLoadedCookies")); 1375 "457528 CookieMonster::StoreLoadedCookies"));
1411 1376
1412 // Initialize the store and sync in any saved persistent cookies. We don't 1377 // Even if a key is expired, insert it so it can be garbage collected,
1413 // care if it's expired, insert it so it can be garbage collected, removed, 1378 // removed, and sync'd.
1414 // and sync'd.
1415 base::AutoLock autolock(lock_);
1416
1417 CookieItVector cookies_with_control_chars; 1379 CookieItVector cookies_with_control_chars;
1418 1380
1419 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin(); 1381 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1420 it != cookies.end(); ++it) { 1382 it != cookies.end(); ++it) {
1421 int64_t cookie_creation_time = (*it)->CreationDate().ToInternalValue(); 1383 int64_t cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1422 1384
1423 if (creation_times_.insert(cookie_creation_time).second) { 1385 if (creation_times_.insert(cookie_creation_time).second) {
1424 CookieMap::iterator inserted = 1386 CookieMap::iterator inserted =
1425 InternalInsertCookie(GetKey((*it)->Domain()), *it, false); 1387 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
1426 const Time cookie_access_time((*it)->LastAccessDate()); 1388 const Time cookie_access_time((*it)->LastAccessDate());
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1459 // none of our other constraints are violated. 1421 // none of our other constraints are violated.
1460 // In particular, the backing store might have given us duplicate cookies. 1422 // In particular, the backing store might have given us duplicate cookies.
1461 1423
1462 // This method could be called multiple times due to priority loading, thus 1424 // This method could be called multiple times due to priority loading, thus
1463 // cookies loaded in previous runs will be validated again, but this is OK 1425 // cookies loaded in previous runs will be validated again, but this is OK
1464 // since they are expected to be much fewer than total DB. 1426 // since they are expected to be much fewer than total DB.
1465 EnsureCookiesMapIsValid(); 1427 EnsureCookiesMapIsValid();
1466 } 1428 }
1467 1429
1468 void CookieMonster::InvokeQueue() { 1430 void CookieMonster::InvokeQueue() {
1469 while (true) { 1431 DCHECK(thread_checker_.CalledOnValidThread());
1470 scoped_refptr<CookieMonsterTask> request_task; 1432
1471 { 1433 while (!tasks_pending_.empty()) {
1472 base::AutoLock autolock(lock_); 1434 scoped_refptr<CookieMonsterTask> request_task = tasks_pending_.front();
1473 if (tasks_pending_.empty()) { 1435 tasks_pending_.pop();
1474 finished_fetching_all_cookies_ = true;
1475 creation_times_.clear();
1476 keys_loaded_.clear();
1477 break;
1478 }
1479 request_task = tasks_pending_.front();
1480 tasks_pending_.pop();
1481 }
1482 request_task->Run(); 1436 request_task->Run();
1483 } 1437 }
1438
1439 finished_fetching_all_cookies_ = true;
1440 creation_times_.clear();
1441 keys_loaded_.clear();
1484 } 1442 }
1485 1443
1486 void CookieMonster::EnsureCookiesMapIsValid() { 1444 void CookieMonster::EnsureCookiesMapIsValid() {
1487 lock_.AssertAcquired(); 1445 DCHECK(thread_checker_.CalledOnValidThread());
1488 1446
1489 // Iterate through all the of the cookies, grouped by host. 1447 // Iterate through all the of the cookies, grouped by host.
1490 CookieMap::iterator prev_range_end = cookies_.begin(); 1448 CookieMap::iterator prev_range_end = cookies_.begin();
1491 while (prev_range_end != cookies_.end()) { 1449 while (prev_range_end != cookies_.end()) {
1492 CookieMap::iterator cur_range_begin = prev_range_end; 1450 CookieMap::iterator cur_range_begin = prev_range_end;
1493 const std::string key = cur_range_begin->first; // Keep a copy. 1451 const std::string key = cur_range_begin->first; // Keep a copy.
1494 CookieMap::iterator cur_range_end = cookies_.upper_bound(key); 1452 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1495 prev_range_end = cur_range_end; 1453 prev_range_end = cur_range_end;
1496 1454
1497 // Ensure no equivalent cookies for this host. 1455 // Ensure no equivalent cookies for this host.
1498 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end); 1456 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
1499 } 1457 }
1500 } 1458 }
1501 1459
1502 void CookieMonster::TrimDuplicateCookiesForKey(const std::string& key, 1460 void CookieMonster::TrimDuplicateCookiesForKey(const std::string& key,
1503 CookieMap::iterator begin, 1461 CookieMap::iterator begin,
1504 CookieMap::iterator end) { 1462 CookieMap::iterator end) {
1505 lock_.AssertAcquired(); 1463 DCHECK(thread_checker_.CalledOnValidThread());
1506 1464
1507 // Set of cookies ordered by creation time. 1465 // Set of cookies ordered by creation time.
1508 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet; 1466 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1509 1467
1510 // Helper map we populate to find the duplicates. 1468 // Helper map we populate to find the duplicates.
1511 typedef std::map<CookieSignature, CookieSet> EquivalenceMap; 1469 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1512 EquivalenceMap equivalent_cookies; 1470 EquivalenceMap equivalent_cookies;
1513 1471
1514 // The number of duplicate cookies that have been found. 1472 // The number of duplicate cookies that have been found.
1515 int num_duplicates = 0; 1473 int num_duplicates = 0;
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
1571 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE); 1529 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1572 } 1530 }
1573 } 1531 }
1574 DCHECK_EQ(num_duplicates, num_duplicates_found); 1532 DCHECK_EQ(num_duplicates, num_duplicates_found);
1575 } 1533 }
1576 1534
1577 void CookieMonster::FindCookiesForHostAndDomain( 1535 void CookieMonster::FindCookiesForHostAndDomain(
1578 const GURL& url, 1536 const GURL& url,
1579 const CookieOptions& options, 1537 const CookieOptions& options,
1580 std::vector<CanonicalCookie*>* cookies) { 1538 std::vector<CanonicalCookie*>* cookies) {
1581 lock_.AssertAcquired(); 1539 DCHECK(thread_checker_.CalledOnValidThread());
1582 1540
1583 const Time current_time(CurrentTime()); 1541 const Time current_time(CurrentTime());
1584 1542
1585 // Probe to save statistics relatively frequently. We do it here rather 1543 // Probe to save statistics relatively frequently. We do it here rather
1586 // than in the set path as many websites won't set cookies, and we 1544 // than in the set path as many websites won't set cookies, and we
1587 // want to collect statistics whenever the browser's being used. 1545 // want to collect statistics whenever the browser's being used.
1588 RecordPeriodicStats(current_time); 1546 RecordPeriodicStats(current_time);
1589 1547
1590 // Can just dispatch to FindCookiesForKey 1548 // Can just dispatch to FindCookiesForKey
1591 const std::string key(GetKey(url.host())); 1549 const std::string key(GetKey(url.host()));
1592 FindCookiesForKey(key, url, options, current_time, cookies); 1550 FindCookiesForKey(key, url, options, current_time, cookies);
1593 } 1551 }
1594 1552
1595 void CookieMonster::FindCookiesForKey(const std::string& key, 1553 void CookieMonster::FindCookiesForKey(const std::string& key,
1596 const GURL& url, 1554 const GURL& url,
1597 const CookieOptions& options, 1555 const CookieOptions& options,
1598 const Time& current, 1556 const Time& current,
1599 std::vector<CanonicalCookie*>* cookies) { 1557 std::vector<CanonicalCookie*>* cookies) {
1600 lock_.AssertAcquired(); 1558 DCHECK(thread_checker_.CalledOnValidThread());
1601 1559
1602 for (CookieMapItPair its = cookies_.equal_range(key); 1560 for (CookieMapItPair its = cookies_.equal_range(key);
1603 its.first != its.second;) { 1561 its.first != its.second;) {
1604 CookieMap::iterator curit = its.first; 1562 CookieMap::iterator curit = its.first;
1605 CanonicalCookie* cc = curit->second; 1563 CanonicalCookie* cc = curit->second;
1606 ++its.first; 1564 ++its.first;
1607 1565
1608 // If the cookie is expired, delete it. 1566 // If the cookie is expired, delete it.
1609 if (cc->IsExpired(current)) { 1567 if (cc->IsExpired(current)) {
1610 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED); 1568 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
(...skipping 13 matching lines...) Expand all
1624 } 1582 }
1625 cookies->push_back(cc); 1583 cookies->push_back(cc);
1626 } 1584 }
1627 } 1585 }
1628 1586
1629 bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key, 1587 bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1630 const CanonicalCookie& ecc, 1588 const CanonicalCookie& ecc,
1631 bool skip_httponly, 1589 bool skip_httponly,
1632 bool already_expired, 1590 bool already_expired,
1633 bool enforce_strict_secure) { 1591 bool enforce_strict_secure) {
1634 lock_.AssertAcquired(); 1592 DCHECK(thread_checker_.CalledOnValidThread());
1635 1593
1636 bool found_equivalent_cookie = false; 1594 bool found_equivalent_cookie = false;
1637 bool skipped_httponly = false; 1595 bool skipped_httponly = false;
1638 bool skipped_secure_cookie = false; 1596 bool skipped_secure_cookie = false;
1639 1597
1640 histogram_cookie_delete_equivalent_->Add(COOKIE_DELETE_EQUIVALENT_ATTEMPT); 1598 histogram_cookie_delete_equivalent_->Add(COOKIE_DELETE_EQUIVALENT_ATTEMPT);
1641 1599
1642 for (CookieMapItPair its = cookies_.equal_range(key); 1600 for (CookieMapItPair its = cookies_.equal_range(key);
1643 its.first != its.second;) { 1601 its.first != its.second;) {
1644 CookieMap::iterator curit = its.first; 1602 CookieMap::iterator curit = its.first;
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
1687 found_equivalent_cookie = true; 1645 found_equivalent_cookie = true;
1688 } 1646 }
1689 } 1647 }
1690 return skipped_httponly || skipped_secure_cookie; 1648 return skipped_httponly || skipped_secure_cookie;
1691 } 1649 }
1692 1650
1693 CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie( 1651 CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1694 const std::string& key, 1652 const std::string& key,
1695 CanonicalCookie* cc, 1653 CanonicalCookie* cc,
1696 bool sync_to_store) { 1654 bool sync_to_store) {
1655 DCHECK(thread_checker_.CalledOnValidThread());
1656
1697 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed. 1657 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
1698 tracked_objects::ScopedTracker tracking_profile( 1658 tracked_objects::ScopedTracker tracking_profile(
1699 FROM_HERE_WITH_EXPLICIT_FUNCTION( 1659 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1700 "456373 CookieMonster::InternalInsertCookie")); 1660 "456373 CookieMonster::InternalInsertCookie"));
1701 lock_.AssertAcquired();
1702 1661
1703 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() && 1662 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1704 sync_to_store) 1663 sync_to_store)
1705 store_->AddCookie(*cc); 1664 store_->AddCookie(*cc);
1706 CookieMap::iterator inserted = 1665 CookieMap::iterator inserted =
1707 cookies_.insert(CookieMap::value_type(key, cc)); 1666 cookies_.insert(CookieMap::value_type(key, cc));
1708 if (delegate_.get()) { 1667 if (delegate_.get()) {
1709 delegate_->OnCookieChanged(*cc, false, 1668 delegate_->OnCookieChanged(*cc, false,
1710 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT); 1669 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT);
1711 } 1670 }
(...skipping 17 matching lines...) Expand all
1729 : COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME; 1688 : COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME;
1730 } else { 1689 } else {
1731 cookie_source_sample = 1690 cookie_source_sample =
1732 cc->IsSecure() 1691 cc->IsSecure()
1733 ? COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME 1692 ? COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME
1734 : COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME; 1693 : COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME;
1735 } 1694 }
1736 histogram_cookie_source_scheme_->Add(cookie_source_sample); 1695 histogram_cookie_source_scheme_->Add(cookie_source_sample);
1737 } 1696 }
1738 1697
1739 RunCallbacks(*cc, false); 1698 RunCookieChangedCallbacks(*cc, false);
1740 1699
1741 return inserted; 1700 return inserted;
1742 } 1701 }
1743 1702
1744 bool CookieMonster::SetCookieWithCreationTimeAndOptions( 1703 bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1745 const GURL& url, 1704 const GURL& url,
1746 const std::string& cookie_line, 1705 const std::string& cookie_line,
1747 const Time& creation_time_or_null, 1706 const Time& creation_time_or_null,
1748 const CookieOptions& options) { 1707 const CookieOptions& options) {
1749 lock_.AssertAcquired(); 1708 DCHECK(thread_checker_.CalledOnValidThread());
1750 1709
1751 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line; 1710 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
1752 1711
1753 Time creation_time = creation_time_or_null; 1712 Time creation_time = creation_time_or_null;
1754 if (creation_time.is_null()) { 1713 if (creation_time.is_null()) {
1755 creation_time = CurrentTime(); 1714 creation_time = CurrentTime();
1756 last_time_seen_ = creation_time; 1715 last_time_seen_ = creation_time;
1757 } 1716 }
1758 1717
1759 scoped_ptr<CanonicalCookie> cc( 1718 scoped_ptr<CanonicalCookie> cc(
1760 CanonicalCookie::Create(url, cookie_line, creation_time, options)); 1719 CanonicalCookie::Create(url, cookie_line, creation_time, options));
1761 1720
1762 if (!cc.get()) { 1721 if (!cc.get()) {
1763 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie"; 1722 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
1764 return false; 1723 return false;
1765 } 1724 }
1766 return SetCanonicalCookie(std::move(cc), options); 1725 return SetCanonicalCookie(std::move(cc), options);
1767 } 1726 }
1768 1727
1769 bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc, 1728 bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc,
1770 const CookieOptions& options) { 1729 const CookieOptions& options) {
1730 DCHECK(thread_checker_.CalledOnValidThread());
1731
1771 Time creation_time = cc->CreationDate(); 1732 Time creation_time = cc->CreationDate();
1772 const std::string key(GetKey(cc->Domain())); 1733 const std::string key(GetKey(cc->Domain()));
1773 bool already_expired = cc->IsExpired(creation_time); 1734 bool already_expired = cc->IsExpired(creation_time);
1774 1735
1775 if (DeleteAnyEquivalentCookie(key, *cc, options.exclude_httponly(), 1736 if (DeleteAnyEquivalentCookie(key, *cc, options.exclude_httponly(),
1776 already_expired, 1737 already_expired,
1777 options.enforce_strict_secure())) { 1738 options.enforce_strict_secure())) {
1778 std::string error; 1739 std::string error;
1779 if (options.enforce_strict_secure()) { 1740 if (options.enforce_strict_secure()) {
1780 error = 1741 error =
(...skipping 28 matching lines...) Expand all
1809 // querying a cookie. Since setting a cookie can put us over our limits, 1770 // querying a cookie. Since setting a cookie can put us over our limits,
1810 // make sure that we garbage collect... We can also make the assumption that 1771 // make sure that we garbage collect... We can also make the assumption that
1811 // if a cookie was set, in the common case it will be used soon after, 1772 // if a cookie was set, in the common case it will be used soon after,
1812 // and we will purge the expired cookies in GetCookies(). 1773 // and we will purge the expired cookies in GetCookies().
1813 GarbageCollect(creation_time, key, options.enforce_strict_secure()); 1774 GarbageCollect(creation_time, key, options.enforce_strict_secure());
1814 1775
1815 return true; 1776 return true;
1816 } 1777 }
1817 1778
1818 bool CookieMonster::SetCanonicalCookies(const CookieList& list) { 1779 bool CookieMonster::SetCanonicalCookies(const CookieList& list) {
1819 base::AutoLock autolock(lock_); 1780 DCHECK(thread_checker_.CalledOnValidThread());
1820 1781
1821 CookieOptions options; 1782 CookieOptions options;
1822 options.set_include_httponly(); 1783 options.set_include_httponly();
1823 1784
1824 for (const auto& cookie : list) { 1785 for (const auto& cookie : list) {
1825 if (!SetCanonicalCookie(make_scoped_ptr(new CanonicalCookie(cookie)), 1786 if (!SetCanonicalCookie(make_scoped_ptr(new CanonicalCookie(cookie)),
1826 options)) { 1787 options)) {
1827 return false; 1788 return false;
1828 } 1789 }
1829 } 1790 }
1830 1791
1831 return true; 1792 return true;
1832 } 1793 }
1833 1794
1834 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc, 1795 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1835 const Time& current) { 1796 const Time& current) {
1836 lock_.AssertAcquired(); 1797 DCHECK(thread_checker_.CalledOnValidThread());
1837 1798
1838 // Based off the Mozilla code. When a cookie has been accessed recently, 1799 // Based off the Mozilla code. When a cookie has been accessed recently,
1839 // don't bother updating its access time again. This reduces the number of 1800 // don't bother updating its access time again. This reduces the number of
1840 // updates we do during pageload, which in turn reduces the chance our storage 1801 // updates we do during pageload, which in turn reduces the chance our storage
1841 // backend will hit its batch thresholds and be forced to update. 1802 // backend will hit its batch thresholds and be forced to update.
1842 if ((current - cc->LastAccessDate()) < last_access_threshold_) 1803 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1843 return; 1804 return;
1844 1805
1845 cc->SetLastAccessDate(current); 1806 cc->SetLastAccessDate(current);
1846 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get()) 1807 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
1847 store_->UpdateCookieAccessTime(*cc); 1808 store_->UpdateCookieAccessTime(*cc);
1848 } 1809 }
1849 1810
1850 // InternalDeleteCookies must not invalidate iterators other than the one being 1811 // InternalDeleteCookies must not invalidate iterators other than the one being
1851 // deleted. 1812 // deleted.
1852 void CookieMonster::InternalDeleteCookie(CookieMap::iterator it, 1813 void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
1853 bool sync_to_store, 1814 bool sync_to_store,
1854 DeletionCause deletion_cause) { 1815 DeletionCause deletion_cause) {
1855 lock_.AssertAcquired(); 1816 DCHECK(thread_checker_.CalledOnValidThread());
1856 1817
1857 // Ideally, this would be asserted up where we define ChangeCauseMapping, 1818 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1858 // but DeletionCause's visibility (or lack thereof) forces us to make 1819 // but DeletionCause's visibility (or lack thereof) forces us to make
1859 // this check here. 1820 // this check here.
1860 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1, 1821 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
1861 "ChangeCauseMapping size should match DeletionCause size"); 1822 "ChangeCauseMapping size should match DeletionCause size");
1862 1823
1863 // See InitializeHistograms() for details. 1824 // See InitializeHistograms() for details.
1864 if (deletion_cause != DELETE_COOKIE_DONT_RECORD) 1825 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
1865 histogram_cookie_deletion_cause_->Add(deletion_cause); 1826 histogram_cookie_deletion_cause_->Add(deletion_cause);
1866 1827
1867 CanonicalCookie* cc = it->second; 1828 CanonicalCookie* cc = it->second;
1868 VLOG(kVlogSetCookies) << "InternalDeleteCookie()" 1829 VLOG(kVlogSetCookies) << "InternalDeleteCookie()"
1869 << ", cause:" << deletion_cause 1830 << ", cause:" << deletion_cause
1870 << ", cc: " << cc->DebugString(); 1831 << ", cc: " << cc->DebugString();
1871 1832
1872 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() && 1833 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1873 sync_to_store) 1834 sync_to_store)
1874 store_->DeleteCookie(*cc); 1835 store_->DeleteCookie(*cc);
1875 if (delegate_.get()) { 1836 if (delegate_.get()) {
1876 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause]; 1837 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
1877 1838
1878 if (mapping.notify) 1839 if (mapping.notify)
1879 delegate_->OnCookieChanged(*cc, true, mapping.cause); 1840 delegate_->OnCookieChanged(*cc, true, mapping.cause);
1880 } 1841 }
1881 RunCallbacks(*cc, true); 1842 RunCookieChangedCallbacks(*cc, true);
1882 cookies_.erase(it); 1843 cookies_.erase(it);
1883 delete cc; 1844 delete cc;
1884 } 1845 }
1885 1846
1886 // Domain expiry behavior is unchanged by key/expiry scheme (the 1847 // Domain expiry behavior is unchanged by key/expiry scheme (the
1887 // meaning of the key is different, but that's not visible to this routine). 1848 // meaning of the key is different, but that's not visible to this routine).
1888 size_t CookieMonster::GarbageCollect(const Time& current, 1849 size_t CookieMonster::GarbageCollect(const Time& current,
1889 const std::string& key, 1850 const std::string& key,
1890 bool enforce_strict_secure) { 1851 bool enforce_strict_secure) {
1891 lock_.AssertAcquired(); 1852 DCHECK(thread_checker_.CalledOnValidThread());
1892 1853
1893 size_t num_deleted = 0; 1854 size_t num_deleted = 0;
1894 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays)); 1855 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
1895 1856
1896 // Collect garbage for this key, minding cookie priorities. 1857 // Collect garbage for this key, minding cookie priorities.
1897 if (cookies_.count(key) > kDomainMaxCookies) { 1858 if (cookies_.count(key) > kDomainMaxCookies) {
1898 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key; 1859 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
1899 1860
1900 CookieItVector cookie_its; 1861 CookieItVector cookie_its;
1901 1862
(...skipping 209 matching lines...) Expand 10 before | Expand all | Expand 10 after
2111 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle, 2072 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle,
2112 it_purge_end); 2073 it_purge_end);
2113 it_purge_begin = it_purge_end; 2074 it_purge_begin = it_purge_end;
2114 } 2075 }
2115 return num_deleted; 2076 return num_deleted;
2116 } 2077 }
2117 2078
2118 size_t CookieMonster::GarbageCollectExpired(const Time& current, 2079 size_t CookieMonster::GarbageCollectExpired(const Time& current,
2119 const CookieMapItPair& itpair, 2080 const CookieMapItPair& itpair,
2120 CookieItVector* cookie_its) { 2081 CookieItVector* cookie_its) {
2121 lock_.AssertAcquired(); 2082 DCHECK(thread_checker_.CalledOnValidThread());
2122 2083
2123 int num_deleted = 0; 2084 int num_deleted = 0;
2124 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) { 2085 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2125 CookieMap::iterator curit = it; 2086 CookieMap::iterator curit = it;
2126 ++it; 2087 ++it;
2127 2088
2128 if (curit->second->IsExpired(current)) { 2089 if (curit->second->IsExpired(current)) {
2129 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED); 2090 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
2130 ++num_deleted; 2091 ++num_deleted;
2131 } else if (cookie_its) { 2092 } else if (cookie_its) {
2132 cookie_its->push_back(curit); 2093 cookie_its->push_back(curit);
2133 } 2094 }
2134 } 2095 }
2135 2096
2136 return num_deleted; 2097 return num_deleted;
2137 } 2098 }
2138 2099
2139 size_t CookieMonster::GarbageCollectNonSecure( 2100 size_t CookieMonster::GarbageCollectNonSecure(
2140 const CookieItVector& valid_cookies, 2101 const CookieItVector& valid_cookies,
2141 CookieItVector* cookie_its) { 2102 CookieItVector* cookie_its) {
2142 lock_.AssertAcquired(); 2103 DCHECK(thread_checker_.CalledOnValidThread());
2143 2104
2144 size_t num_deleted = 0; 2105 size_t num_deleted = 0;
2145 for (const auto& curr_cookie_it : valid_cookies) { 2106 for (const auto& curr_cookie_it : valid_cookies) {
2146 if (!curr_cookie_it->second->IsSecure()) { 2107 if (!curr_cookie_it->second->IsSecure()) {
2147 InternalDeleteCookie(curr_cookie_it, true, DELETE_COOKIE_NON_SECURE); 2108 InternalDeleteCookie(curr_cookie_it, true, DELETE_COOKIE_NON_SECURE);
2148 ++num_deleted; 2109 ++num_deleted;
2149 } else if (cookie_its) { 2110 } else if (cookie_its) {
2150 cookie_its->push_back(curr_cookie_it); 2111 cookie_its->push_back(curr_cookie_it);
2151 } 2112 }
2152 } 2113 }
2153 2114
2154 return num_deleted; 2115 return num_deleted;
2155 } 2116 }
2156 2117
2157 size_t CookieMonster::GarbageCollectDeleteRange( 2118 size_t CookieMonster::GarbageCollectDeleteRange(
2158 const Time& current, 2119 const Time& current,
2159 DeletionCause cause, 2120 DeletionCause cause,
2160 CookieItVector::iterator it_begin, 2121 CookieItVector::iterator it_begin,
2161 CookieItVector::iterator it_end) { 2122 CookieItVector::iterator it_end) {
2123 DCHECK(thread_checker_.CalledOnValidThread());
2124
2162 for (CookieItVector::iterator it = it_begin; it != it_end; it++) { 2125 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2163 histogram_evicted_last_access_minutes_->Add( 2126 histogram_evicted_last_access_minutes_->Add(
2164 (current - (*it)->second->LastAccessDate()).InMinutes()); 2127 (current - (*it)->second->LastAccessDate()).InMinutes());
2165 InternalDeleteCookie((*it), true, cause); 2128 InternalDeleteCookie((*it), true, cause);
2166 } 2129 }
2167 return it_end - it_begin; 2130 return it_end - it_begin;
2168 } 2131 }
2169 2132
2170 size_t CookieMonster::GarbageCollectLeastRecentlyAccessed( 2133 size_t CookieMonster::GarbageCollectLeastRecentlyAccessed(
2171 const base::Time& current, 2134 const base::Time& current,
2172 const base::Time& safe_date, 2135 const base::Time& safe_date,
2173 size_t purge_goal, 2136 size_t purge_goal,
2174 CookieItVector cookie_its) { 2137 CookieItVector cookie_its) {
2138 DCHECK(thread_checker_.CalledOnValidThread());
2139
2175 // Sorts up to *and including* |cookie_its[purge_goal]|, so 2140 // Sorts up to *and including* |cookie_its[purge_goal]|, so
2176 // |earliest_access_time| will be properly assigned even if 2141 // |earliest_access_time| will be properly assigned even if
2177 // |global_purge_it| == |cookie_its.begin() + purge_goal|. 2142 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2178 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(), purge_goal); 2143 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(), purge_goal);
2179 // Find boundary to cookies older than safe_date. 2144 // Find boundary to cookies older than safe_date.
2180 CookieItVector::iterator global_purge_it = LowerBoundAccessDate( 2145 CookieItVector::iterator global_purge_it = LowerBoundAccessDate(
2181 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date); 2146 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
2182 // Only delete the old cookies, and if strict secure is enabled, delete 2147 // Only delete the old cookies, and if strict secure is enabled, delete
2183 // non-secure ones first. 2148 // non-secure ones first.
2184 size_t num_deleted = 2149 size_t num_deleted =
(...skipping 21 matching lines...) Expand all
2206 // Arguably the right thing to do here is to make the key 2171 // Arguably the right thing to do here is to make the key
2207 // algorithm dependent on the scheme, and make sure that the scheme is 2172 // algorithm dependent on the scheme, and make sure that the scheme is
2208 // available everywhere the key must be obtained (specfically at backing 2173 // available everywhere the key must be obtained (specfically at backing
2209 // store load time). This would require either changing the backing store 2174 // store load time). This would require either changing the backing store
2210 // database schema to include the scheme (far more trouble than it's worth), or 2175 // database schema to include the scheme (far more trouble than it's worth), or
2211 // separating out file cookies into their own CookieMonster instance and 2176 // separating out file cookies into their own CookieMonster instance and
2212 // thus restricting each scheme to a single cookie monster (which might 2177 // thus restricting each scheme to a single cookie monster (which might
2213 // be worth it, but is still too much trouble to solve what is currently a 2178 // be worth it, but is still too much trouble to solve what is currently a
2214 // non-problem). 2179 // non-problem).
2215 std::string CookieMonster::GetKey(const std::string& domain) const { 2180 std::string CookieMonster::GetKey(const std::string& domain) const {
2181 DCHECK(thread_checker_.CalledOnValidThread());
2182
2216 std::string effective_domain( 2183 std::string effective_domain(
2217 registry_controlled_domains::GetDomainAndRegistry( 2184 registry_controlled_domains::GetDomainAndRegistry(
2218 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)); 2185 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
2219 if (effective_domain.empty()) 2186 if (effective_domain.empty())
2220 effective_domain = domain; 2187 effective_domain = domain;
2221 2188
2222 if (!effective_domain.empty() && effective_domain[0] == '.') 2189 if (!effective_domain.empty() && effective_domain[0] == '.')
2223 return effective_domain.substr(1); 2190 return effective_domain.substr(1);
2224 return effective_domain; 2191 return effective_domain;
2225 } 2192 }
2226 2193
2227 bool CookieMonster::HasCookieableScheme(const GURL& url) { 2194 bool CookieMonster::HasCookieableScheme(const GURL& url) {
2228 lock_.AssertAcquired(); 2195 DCHECK(thread_checker_.CalledOnValidThread());
2229 2196
2230 // Make sure the request is on a cookie-able url scheme. 2197 // Make sure the request is on a cookie-able url scheme.
2231 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) { 2198 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2232 // We matched a scheme. 2199 // We matched a scheme.
2233 if (url.SchemeIs(cookieable_schemes_[i].c_str())) { 2200 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2234 // We've matched a supported scheme. 2201 // We've matched a supported scheme.
2235 return true; 2202 return true;
2236 } 2203 }
2237 } 2204 }
2238 2205
2239 // The scheme didn't match any in our whitelist. 2206 // The scheme didn't match any in our whitelist.
2240 VLOG(kVlogPerCookieMonster) 2207 VLOG(kVlogPerCookieMonster)
2241 << "WARNING: Unsupported cookie scheme: " << url.scheme(); 2208 << "WARNING: Unsupported cookie scheme: " << url.scheme();
2242 return false; 2209 return false;
2243 } 2210 }
2244 2211
2245 // Test to see if stats should be recorded, and record them if so. 2212 // Test to see if stats should be recorded, and record them if so.
2246 // The goal here is to get sampling for the average browser-hour of 2213 // The goal here is to get sampling for the average browser-hour of
2247 // activity. We won't take samples when the web isn't being surfed, 2214 // activity. We won't take samples when the web isn't being surfed,
2248 // and when the web is being surfed, we'll take samples about every 2215 // and when the web is being surfed, we'll take samples about every
2249 // kRecordStatisticsIntervalSeconds. 2216 // kRecordStatisticsIntervalSeconds.
2250 // last_statistic_record_time_ is initialized to Now() rather than null 2217 // last_statistic_record_time_ is initialized to Now() rather than null
2251 // in the constructor so that we won't take statistics right after 2218 // in the constructor so that we won't take statistics right after
2252 // startup, to avoid bias from browsers that are started but not used. 2219 // startup, to avoid bias from browsers that are started but not used.
2253 void CookieMonster::RecordPeriodicStats(const base::Time& current_time) { 2220 void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2221 DCHECK(thread_checker_.CalledOnValidThread());
2222
2254 const base::TimeDelta kRecordStatisticsIntervalTime( 2223 const base::TimeDelta kRecordStatisticsIntervalTime(
2255 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds)); 2224 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2256 2225
2257 // If we've taken statistics recently, return. 2226 // If we've taken statistics recently, return.
2258 if (current_time - last_statistic_record_time_ <= 2227 if (current_time - last_statistic_record_time_ <=
2259 kRecordStatisticsIntervalTime) { 2228 kRecordStatisticsIntervalTime) {
2260 return; 2229 return;
2261 } 2230 }
2262 2231
2263 // See InitializeHistograms() for details. 2232 // See InitializeHistograms() for details.
(...skipping 20 matching lines...) Expand all
2284 // Note that these variables refer to the same underlying histogram, 2253 // Note that these variables refer to the same underlying histogram,
2285 // so we still race (but safely) with other CookieMonster instances 2254 // so we still race (but safely) with other CookieMonster instances
2286 // for accumulation. 2255 // for accumulation.
2287 // 2256 //
2288 // To do this we've expanded out the individual histogram macros calls, 2257 // To do this we've expanded out the individual histogram macros calls,
2289 // with declarations of the variables in the class decl, initialization here 2258 // with declarations of the variables in the class decl, initialization here
2290 // (done from the class constructor) and direct calls to the accumulation 2259 // (done from the class constructor) and direct calls to the accumulation
2291 // methods where needed. The specific histogram macro calls on which the 2260 // methods where needed. The specific histogram macro calls on which the
2292 // initialization is based are included in comments below. 2261 // initialization is based are included in comments below.
2293 void CookieMonster::InitializeHistograms() { 2262 void CookieMonster::InitializeHistograms() {
2263 DCHECK(thread_checker_.CalledOnValidThread());
2264
2294 // From UMA_HISTOGRAM_CUSTOM_COUNTS 2265 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2295 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet( 2266 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
2296 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50, 2267 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50,
2297 base::Histogram::kUmaTargetedHistogramFlag); 2268 base::Histogram::kUmaTargetedHistogramFlag);
2298 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet( 2269 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
2299 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50, 2270 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50,
2300 base::Histogram::kUmaTargetedHistogramFlag); 2271 base::Histogram::kUmaTargetedHistogramFlag);
2301 histogram_count_ = base::Histogram::FactoryGet( 2272 histogram_count_ = base::Histogram::FactoryGet(
2302 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag); 2273 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag);
2303 2274
(...skipping 23 matching lines...) Expand all
2327 // The system resolution is not high enough, so we can have multiple 2298 // The system resolution is not high enough, so we can have multiple
2328 // set cookies that result in the same system time. When this happens, we 2299 // set cookies that result in the same system time. When this happens, we
2329 // increment by one Time unit. Let's hope computers don't get too fast. 2300 // increment by one Time unit. Let's hope computers don't get too fast.
2330 Time CookieMonster::CurrentTime() { 2301 Time CookieMonster::CurrentTime() {
2331 return std::max(Time::Now(), Time::FromInternalValue( 2302 return std::max(Time::Now(), Time::FromInternalValue(
2332 last_time_seen_.ToInternalValue() + 1)); 2303 last_time_seen_.ToInternalValue() + 1));
2333 } 2304 }
2334 2305
2335 void CookieMonster::DoCookieTask( 2306 void CookieMonster::DoCookieTask(
2336 const scoped_refptr<CookieMonsterTask>& task_item) { 2307 const scoped_refptr<CookieMonsterTask>& task_item) {
2337 { 2308 DCHECK(thread_checker_.CalledOnValidThread());
2338 base::AutoLock autolock(lock_); 2309
2339 MarkCookieStoreAsInitialized(); 2310 MarkCookieStoreAsInitialized();
2340 FetchAllCookiesIfNecessary(); 2311 FetchAllCookiesIfNecessary();
2341 if (!finished_fetching_all_cookies_ && store_.get()) { 2312
2342 tasks_pending_.push(task_item); 2313 if (!finished_fetching_all_cookies_ && store_.get()) {
2343 return; 2314 tasks_pending_.push(task_item);
2344 } 2315 return;
2345 } 2316 }
2346 2317
2347 task_item->Run(); 2318 task_item->Run();
2348 } 2319 }
2349 2320
2350 void CookieMonster::DoCookieTaskForURL( 2321 void CookieMonster::DoCookieTaskForURL(
2351 const scoped_refptr<CookieMonsterTask>& task_item, 2322 const scoped_refptr<CookieMonsterTask>& task_item,
2352 const GURL& url) { 2323 const GURL& url) {
2353 { 2324 DCHECK(thread_checker_.CalledOnValidThread());
2354 base::AutoLock autolock(lock_); 2325
2355 MarkCookieStoreAsInitialized(); 2326 MarkCookieStoreAsInitialized();
2356 if (ShouldFetchAllCookiesWhenFetchingAnyCookie()) 2327 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
2357 FetchAllCookiesIfNecessary(); 2328 FetchAllCookiesIfNecessary();
2358 // If cookies for the requested domain key (eTLD+1) have been loaded from DB 2329
2359 // then run the task, otherwise load from DB. 2330 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
2360 if (!finished_fetching_all_cookies_ && store_.get()) { 2331 // then run the task, otherwise load from DB.
2361 // Checks if the domain key has been loaded. 2332 if (!finished_fetching_all_cookies_ && store_.get()) {
2362 std::string key( 2333 // Checks if the domain key has been loaded.
2363 cookie_util::GetEffectiveDomain(url.scheme(), url.host())); 2334 std::string key(cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
2364 if (keys_loaded_.find(key) == keys_loaded_.end()) { 2335 if (keys_loaded_.find(key) == keys_loaded_.end()) {
2365 std::map<std::string, 2336 std::map<std::string,
2366 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it = 2337 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
2367 tasks_pending_for_key_.find(key); 2338 tasks_pending_for_key_.find(key);
2368 if (it == tasks_pending_for_key_.end()) { 2339 if (it == tasks_pending_for_key_.end()) {
2369 store_->LoadCookiesForKey( 2340 store_->LoadCookiesForKey(
2370 key, base::Bind(&CookieMonster::OnKeyLoaded, this, key)); 2341 key, base::Bind(&CookieMonster::OnKeyLoaded,
2371 it = tasks_pending_for_key_ 2342 weak_ptr_factory_.GetWeakPtr(), key));
2372 .insert(std::make_pair( 2343 it = tasks_pending_for_key_
2373 key, std::deque<scoped_refptr<CookieMonsterTask>>())) 2344 .insert(std::make_pair(
2374 .first; 2345 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
2375 } 2346 .first;
2376 it->second.push_back(task_item);
2377 return;
2378 } 2347 }
2348 it->second.push_back(task_item);
2349 return;
2379 } 2350 }
2380 } 2351 }
2352
2381 task_item->Run(); 2353 task_item->Run();
2382 } 2354 }
2383 2355
2384 void CookieMonster::ComputeCookieDiff(CookieList* old_cookies, 2356 void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2385 CookieList* new_cookies, 2357 CookieList* new_cookies,
2386 CookieList* cookies_to_add, 2358 CookieList* cookies_to_add,
2387 CookieList* cookies_to_delete) { 2359 CookieList* cookies_to_delete) {
2360 DCHECK(thread_checker_.CalledOnValidThread());
2361
2388 DCHECK(old_cookies); 2362 DCHECK(old_cookies);
2389 DCHECK(new_cookies); 2363 DCHECK(new_cookies);
2390 DCHECK(cookies_to_add); 2364 DCHECK(cookies_to_add);
2391 DCHECK(cookies_to_delete); 2365 DCHECK(cookies_to_delete);
2392 DCHECK(cookies_to_add->empty()); 2366 DCHECK(cookies_to_add->empty());
2393 DCHECK(cookies_to_delete->empty()); 2367 DCHECK(cookies_to_delete->empty());
2394 2368
2395 // Sort both lists. 2369 // Sort both lists.
2396 // A set ordered by FullDiffCookieSorter is also ordered by 2370 // A set ordered by FullDiffCookieSorter is also ordered by
2397 // PartialDiffCookieSorter. 2371 // PartialDiffCookieSorter.
2398 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter); 2372 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter);
2399 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter); 2373 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter);
2400 2374
2401 // Select any old cookie for deletion if no new cookie has the same name, 2375 // Select any old cookie for deletion if no new cookie has the same name,
2402 // domain, and path. 2376 // domain, and path.
2403 std::set_difference( 2377 std::set_difference(
2404 old_cookies->begin(), old_cookies->end(), new_cookies->begin(), 2378 old_cookies->begin(), old_cookies->end(), new_cookies->begin(),
2405 new_cookies->end(), 2379 new_cookies->end(),
2406 std::inserter(*cookies_to_delete, cookies_to_delete->begin()), 2380 std::inserter(*cookies_to_delete, cookies_to_delete->begin()),
2407 PartialDiffCookieSorter); 2381 PartialDiffCookieSorter);
2408 2382
2409 // Select any new cookie for addition (or update) if no old cookie is exactly 2383 // Select any new cookie for addition (or update) if no old cookie is exactly
2410 // equivalent. 2384 // equivalent.
2411 std::set_difference(new_cookies->begin(), new_cookies->end(), 2385 std::set_difference(new_cookies->begin(), new_cookies->end(),
2412 old_cookies->begin(), old_cookies->end(), 2386 old_cookies->begin(), old_cookies->end(),
2413 std::inserter(*cookies_to_add, cookies_to_add->begin()), 2387 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2414 FullDiffCookieSorter); 2388 FullDiffCookieSorter);
2415 } 2389 }
2416 2390
2417 void CookieMonster::RunCallbacks(const CanonicalCookie& cookie, bool removed) { 2391 void CookieMonster::RunCallback(const base::Closure& callback) {
2418 lock_.AssertAcquired(); 2392 DCHECK(thread_checker_.CalledOnValidThread());
2393 callback.Run();
2394 }
2395
2396 void CookieMonster::RunCookieChangedCallbacks(const CanonicalCookie& cookie,
2397 bool removed) {
2398 DCHECK(thread_checker_.CalledOnValidThread());
2399
2419 CookieOptions opts; 2400 CookieOptions opts;
2420 opts.set_include_httponly(); 2401 opts.set_include_httponly();
2421 opts.set_include_same_site(); 2402 opts.set_include_same_site();
2422 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they 2403 // Note that the callbacks in hook_map_ are wrapped with RunAsync(), so they
2423 // are guaranteed to not take long - they just post a RunAsync task back to 2404 // are guaranteed to not take long - they just post a RunAsync task back to
2424 // the appropriate thread's message loop and return. It is important that this 2405 // the appropriate thread's message loop and return.
2425 // method not run user-supplied callbacks directly, since the CookieMonster 2406 // TODO(mmenke): Consider running these synchronously?
2426 // lock is held and it is easy to accidentally introduce deadlocks.
2427 for (CookieChangedHookMap::iterator it = hook_map_.begin(); 2407 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2428 it != hook_map_.end(); ++it) { 2408 it != hook_map_.end(); ++it) {
2429 std::pair<GURL, std::string> key = it->first; 2409 std::pair<GURL, std::string> key = it->first;
2430 if (cookie.IncludeForRequestURL(key.first, opts) && 2410 if (cookie.IncludeForRequestURL(key.first, opts) &&
2431 cookie.Name() == key.second) { 2411 cookie.Name() == key.second) {
2432 it->second->Notify(cookie, removed); 2412 it->second->Notify(cookie, removed);
2433 } 2413 }
2434 } 2414 }
2435 } 2415 }
2436 2416
2437 } // namespace net 2417 } // namespace net
OLDNEW
« no previous file with comments | « net/cookies/cookie_monster.h ('k') | net/cookies/cookie_monster_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698