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

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

Issue 2971323002: Switch cookie async mechanism over to using callbacks. (Closed)
Patch Set: Incorporated comments. Created 3 years, 5 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_perftest.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 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
75 75
76 // In steady state, most cookie requests can be satisfied by the in memory 76 // In steady state, most cookie requests can be satisfied by the in memory
77 // cookie monster store. If the cookie request cannot be satisfied by the in 77 // cookie monster store. If the cookie request cannot be satisfied by the in
78 // memory store, the relevant cookies must be fetched from the persistent 78 // memory store, the relevant cookies must be fetched from the persistent
79 // store. The task is queued in CookieMonster::tasks_pending_ if it requires 79 // store. The task is queued in CookieMonster::tasks_pending_ if it requires
80 // all cookies to be loaded from the backend, or tasks_pending_for_key_ if it 80 // all cookies to be loaded from the backend, or tasks_pending_for_key_ if it
81 // only requires all cookies associated with an eTLD+1. 81 // only requires all cookies associated with an eTLD+1.
82 // 82 //
83 // On the browser critical paths (e.g. for loading initial web pages in a 83 // On the browser critical paths (e.g. for loading initial web pages in a
84 // session restore) it may take too long to wait for the full load. If a cookie 84 // session restore) it may take too long to wait for the full load. If a cookie
85 // request is for a specific URL, DoCookieTaskForURL is called, which triggers a 85 // request is for a specific URL, DoCookieCallbackForURL is called, which
86 // priority load if the key is not loaded yet by calling PersistentCookieStore 86 // triggers a priority load if the key is not loaded yet by calling
87 // :: LoadCookiesForKey. The request is queued in 87 // PersistentCookieStore::LoadCookiesForKey. The request is queued in
88 // CookieMonster::tasks_pending_for_key_ and executed upon receiving 88 // CookieMonster::tasks_pending_for_key_ and executed upon receiving
89 // notification of key load completion via CookieMonster::OnKeyLoaded(). If 89 // notification of key load completion via CookieMonster::OnKeyLoaded(). If
90 // multiple requests for the same eTLD+1 are received before key load 90 // multiple requests for the same eTLD+1 are received before key load
91 // completion, only the first request calls 91 // completion, only the first request calls
92 // PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued 92 // PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
93 // in CookieMonster::tasks_pending_for_key_ and executed upon receiving 93 // in CookieMonster::tasks_pending_for_key_ and executed upon receiving
94 // notification of key load completion triggered by the first request for the 94 // notification of key load completion triggered by the first request for the
95 // same eTLD+1. 95 // same eTLD+1.
96 96
97 static const int kMinutesInTenYears = 10 * 365 * 24 * 60; 97 static const int kMinutesInTenYears = 10 * 365 * 24 * 60;
98 98
99 namespace { 99 namespace {
100 100
101 const char kFetchWhenNecessaryName[] = "FetchWhenNecessary"; 101 const char kFetchWhenNecessaryName[] = "FetchWhenNecessary";
102 const char kAlwaysFetchName[] = "AlwaysFetch"; 102 const char kAlwaysFetchName[] = "AlwaysFetch";
103 const char kCookieMonsterFetchStrategyName[] = "CookieMonsterFetchStrategy"; 103 const char kCookieMonsterFetchStrategyName[] = "CookieMonsterFetchStrategy";
104 104
105 void MayeRunDeleteCallback(base::WeakPtr<net::CookieMonster> cookie_monster,
106 base::OnceClosure callback) {
107 if (cookie_monster && callback)
108 std::move(callback).Run();
109 }
110
111 void MaybeRunCookieCallback(base::OnceClosure callback) {
112 if (callback)
113 std::move(callback).Run();
114 }
115
116 template <typename T>
117 void MaybeRunCookieCallback(base::OnceCallback<void(const T&)> callback,
118 const T& result) {
119 if (callback)
120 std::move(callback).Run(result);
121 }
122
123 template <typename T>
124 void MaybeRunCookieCallback(base::OnceCallback<void(T)> callback,
125 const T& result) {
126 if (callback)
127 std::move(callback).Run(result);
128 }
129
105 } // namespace 130 } // namespace
106 131
107 namespace net { 132 namespace net {
108 133
109 // See comments at declaration of these variables in cookie_monster.h 134 // See comments at declaration of these variables in cookie_monster.h
110 // for details. 135 // for details.
111 const size_t CookieMonster::kDomainMaxCookies = 180; 136 const size_t CookieMonster::kDomainMaxCookies = 180;
112 const size_t CookieMonster::kDomainPurgeCookies = 30; 137 const size_t CookieMonster::kDomainPurgeCookies = 30;
113 const size_t CookieMonster::kMaxCookies = 3300; 138 const size_t CookieMonster::kMaxCookies = 3300;
114 const size_t CookieMonster::kPurgeCookies = 300; 139 const size_t CookieMonster::kPurgeCookies = 300;
(...skipping 263 matching lines...) Expand 10 before | Expand all | Expand 10 after
378 channel_id_service_(channel_id_service), 403 channel_id_service_(channel_id_service),
379 last_statistic_record_time_(base::Time::Now()), 404 last_statistic_record_time_(base::Time::Now()),
380 persist_session_cookies_(false), 405 persist_session_cookies_(false),
381 weak_ptr_factory_(this) { 406 weak_ptr_factory_(this) {
382 InitializeHistograms(); 407 InitializeHistograms();
383 cookieable_schemes_.insert( 408 cookieable_schemes_.insert(
384 cookieable_schemes_.begin(), kDefaultCookieableSchemes, 409 cookieable_schemes_.begin(), kDefaultCookieableSchemes,
385 kDefaultCookieableSchemes + kDefaultCookieableSchemesCount); 410 kDefaultCookieableSchemes + kDefaultCookieableSchemesCount);
386 } 411 }
387 412
388 // Task classes for queueing the coming request.
389
390 class CookieMonster::CookieMonsterTask
391 : public base::RefCountedThreadSafe<CookieMonsterTask> {
392 public:
393 // Runs the task and invokes the client callback on the thread that
394 // originally constructed the task.
395 virtual void Run() = 0;
396
397 protected:
398 explicit CookieMonsterTask(CookieMonster* cookie_monster);
399 virtual ~CookieMonsterTask();
400
401 CookieMonster* cookie_monster() { return cookie_monster_; }
402
403 private:
404 friend class base::RefCountedThreadSafe<CookieMonsterTask>;
405
406 CookieMonster* cookie_monster_;
407
408 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask);
409 };
410
411 CookieMonster::CookieMonsterTask::CookieMonsterTask(
412 CookieMonster* cookie_monster)
413 : cookie_monster_(cookie_monster) {}
414
415 CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
416 }
417
418 // Task class for SetCookieWithDetails call.
419 class CookieMonster::SetCookieWithDetailsTask : public CookieMonsterTask {
420 public:
421 SetCookieWithDetailsTask(CookieMonster* cookie_monster,
422 const GURL& url,
423 const std::string& name,
424 const std::string& value,
425 const std::string& domain,
426 const std::string& path,
427 base::Time creation_time,
428 base::Time expiration_time,
429 base::Time last_access_time,
430 bool secure,
431 bool http_only,
432 CookieSameSite same_site,
433 CookiePriority priority,
434 SetCookiesCallback callback)
435 : CookieMonsterTask(cookie_monster),
436 url_(url),
437 name_(name),
438 value_(value),
439 domain_(domain),
440 path_(path),
441 creation_time_(creation_time),
442 expiration_time_(expiration_time),
443 last_access_time_(last_access_time),
444 secure_(secure),
445 http_only_(http_only),
446 same_site_(same_site),
447 priority_(priority),
448 callback_(std::move(callback)) {}
449
450 // CookieMonsterTask:
451 void Run() override;
452
453 protected:
454 ~SetCookieWithDetailsTask() override {}
455
456 private:
457 GURL url_;
458 std::string name_;
459 std::string value_;
460 std::string domain_;
461 std::string path_;
462 base::Time creation_time_;
463 base::Time expiration_time_;
464 base::Time last_access_time_;
465 bool secure_;
466 bool http_only_;
467 CookieSameSite same_site_;
468 CookiePriority priority_;
469 SetCookiesCallback callback_;
470
471 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask);
472 };
473
474 void CookieMonster::SetCookieWithDetailsTask::Run() {
475 bool success = this->cookie_monster()->SetCookieWithDetails(
476 url_, name_, value_, domain_, path_, creation_time_, expiration_time_,
477 last_access_time_, secure_, http_only_, same_site_, priority_);
478 if (!callback_.is_null())
479 std::move(callback_).Run(success);
480 }
481
482 // Task class for GetAllCookies call.
483 class CookieMonster::GetAllCookiesTask : public CookieMonsterTask {
484 public:
485 GetAllCookiesTask(CookieMonster* cookie_monster,
486 GetCookieListCallback callback)
487 : CookieMonsterTask(cookie_monster), callback_(std::move(callback)) {}
488
489 // CookieMonsterTask
490 void Run() override;
491
492 protected:
493 ~GetAllCookiesTask() override {}
494
495 private:
496 GetCookieListCallback callback_;
497
498 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask);
499 };
500
501 void CookieMonster::GetAllCookiesTask::Run() {
502 if (!callback_.is_null()) {
503 CookieList cookies = this->cookie_monster()->GetAllCookies();
504 std::move(callback_).Run(cookies);
505 }
506 }
507
508 // Task class for GetCookieListWithOptionsAsync call.
509 class CookieMonster::GetCookieListWithOptionsTask : public CookieMonsterTask {
510 public:
511 GetCookieListWithOptionsTask(CookieMonster* cookie_monster,
512 const GURL& url,
513 const CookieOptions& options,
514 GetCookieListCallback callback)
515 : CookieMonsterTask(cookie_monster),
516 url_(url),
517 options_(options),
518 callback_(std::move(callback)) {}
519
520 // CookieMonsterTask:
521 void Run() override;
522
523 protected:
524 ~GetCookieListWithOptionsTask() override {}
525
526 private:
527 GURL url_;
528 CookieOptions options_;
529 GetCookieListCallback callback_;
530
531 DISALLOW_COPY_AND_ASSIGN(GetCookieListWithOptionsTask);
532 };
533
534 void CookieMonster::GetCookieListWithOptionsTask::Run() {
535 if (!callback_.is_null()) {
536 CookieList cookies =
537 this->cookie_monster()->GetCookieListWithOptions(url_, options_);
538 std::move(callback_).Run(cookies);
539 }
540 }
541
542 template <typename Result>
543 struct CallbackType {
544 typedef base::OnceCallback<void(Result)> Type;
545 };
546
547 template <>
548 struct CallbackType<void> {
549 typedef base::OnceClosure Type;
550 };
551
552 // Base task class for Delete*Task.
553 template <typename Result>
554 class CookieMonster::DeleteTask : public CookieMonsterTask {
555 public:
556 DeleteTask(CookieMonster* cookie_monster,
557 typename CallbackType<Result>::Type callback)
558 : CookieMonsterTask(cookie_monster), callback_(std::move(callback)) {}
559
560 // CookieMonsterTask:
561 void Run() override;
562
563 protected:
564 ~DeleteTask() override;
565
566 private:
567 // Runs the delete task and returns a result.
568 virtual Result RunDeleteTask() = 0;
569 // Runs the delete task and then returns a callback to be called after
570 // flushing the persistent store.
571 // TODO(mmenke): This seems like a pretty ugly and needlessly confusing API.
572 // Simplify it?
573 base::OnceClosure RunDeleteTaskAndBindCallback();
574
575 typename CallbackType<Result>::Type callback_;
576
577 DISALLOW_COPY_AND_ASSIGN(DeleteTask);
578 };
579
580 template <typename Result>
581 CookieMonster::DeleteTask<Result>::~DeleteTask() {
582 }
583
584 template <typename Result>
585 base::OnceClosure
586 CookieMonster::DeleteTask<Result>::RunDeleteTaskAndBindCallback() {
587 Result result = RunDeleteTask();
588 if (callback_.is_null())
589 return base::OnceClosure();
590 return base::BindOnce(std::move(callback_), result);
591 }
592
593 template <>
594 base::OnceClosure
595 CookieMonster::DeleteTask<void>::RunDeleteTaskAndBindCallback() {
596 RunDeleteTask();
597 return std::move(callback_);
598 }
599
600 template <typename Result>
601 void CookieMonster::DeleteTask<Result>::Run() {
602 base::OnceClosure callback = RunDeleteTaskAndBindCallback();
603 if (!callback.is_null()) {
604 callback =
605 base::BindOnce(&CookieMonster::RunCallback,
606 this->cookie_monster()->weak_ptr_factory_.GetWeakPtr(),
607 std::move(callback));
608 }
609 this->cookie_monster()->FlushStore(std::move(callback));
610 }
611
612 // Task class for DeleteAllCreatedBetween call.
613 class CookieMonster::DeleteAllCreatedBetweenTask : public DeleteTask<uint32_t> {
614 public:
615 DeleteAllCreatedBetweenTask(CookieMonster* cookie_monster,
616 const Time& delete_begin,
617 const Time& delete_end,
618 DeleteCallback callback)
619 : DeleteTask<uint32_t>(cookie_monster, std::move(callback)),
620 delete_begin_(delete_begin),
621 delete_end_(delete_end) {}
622
623 // DeleteTask:
624 uint32_t RunDeleteTask() override;
625
626 protected:
627 ~DeleteAllCreatedBetweenTask() override {}
628
629 private:
630 Time delete_begin_;
631 Time delete_end_;
632
633 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask);
634 };
635
636 uint32_t CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
637 return this->cookie_monster()->DeleteAllCreatedBetween(delete_begin_,
638 delete_end_);
639 }
640
641 // Task class for DeleteAllCreatedBetweenWithPredicate call.
642 class CookieMonster::DeleteAllCreatedBetweenWithPredicateTask
643 : public DeleteTask<uint32_t> {
644 public:
645 DeleteAllCreatedBetweenWithPredicateTask(
646 CookieMonster* cookie_monster,
647 Time delete_begin,
648 Time delete_end,
649 base::Callback<bool(const CanonicalCookie&)> predicate,
650 DeleteCallback callback)
651 : DeleteTask<uint32_t>(cookie_monster, std::move(callback)),
652 delete_begin_(delete_begin),
653 delete_end_(delete_end),
654 predicate_(predicate) {}
655
656 // DeleteTask:
657 uint32_t RunDeleteTask() override;
658
659 protected:
660 ~DeleteAllCreatedBetweenWithPredicateTask() override {}
661
662 private:
663 Time delete_begin_;
664 Time delete_end_;
665 base::Callback<bool(const CanonicalCookie&)> predicate_;
666
667 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenWithPredicateTask);
668 };
669
670 uint32_t
671 CookieMonster::DeleteAllCreatedBetweenWithPredicateTask::RunDeleteTask() {
672 return this->cookie_monster()->DeleteAllCreatedBetweenWithPredicate(
673 delete_begin_, delete_end_, predicate_);
674 }
675
676 // Task class for DeleteCanonicalCookie call.
677 class CookieMonster::DeleteCanonicalCookieTask : public DeleteTask<uint32_t> {
678 public:
679 DeleteCanonicalCookieTask(CookieMonster* cookie_monster,
680 const CanonicalCookie& cookie,
681 DeleteCallback callback)
682 : DeleteTask<uint32_t>(cookie_monster, std::move(callback)),
683 cookie_(cookie) {}
684
685 // DeleteTask:
686 uint32_t RunDeleteTask() override;
687
688 protected:
689 ~DeleteCanonicalCookieTask() override {}
690
691 private:
692 CanonicalCookie cookie_;
693
694 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask);
695 };
696
697 uint32_t CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
698 return this->cookie_monster()->DeleteCanonicalCookie(cookie_);
699 }
700
701 // Task class for SetCanonicalCookie call.
702 class CookieMonster::SetCanonicalCookieTask : public CookieMonsterTask {
703 public:
704 SetCanonicalCookieTask(CookieMonster* cookie_monster,
705 std::unique_ptr<CanonicalCookie> cookie,
706 bool secure_source,
707 bool modify_http_only,
708 SetCookiesCallback callback)
709 : CookieMonsterTask(cookie_monster),
710 cookie_(std::move(cookie)),
711 secure_source_(secure_source),
712 modify_http_only_(modify_http_only),
713 callback_(std::move(callback)) {}
714
715 // CookieMonsterTask:
716 void Run() override;
717
718 protected:
719 ~SetCanonicalCookieTask() override {}
720
721 private:
722 std::unique_ptr<CanonicalCookie> cookie_;
723 bool secure_source_;
724 bool modify_http_only_;
725 SetCookiesCallback callback_;
726
727 DISALLOW_COPY_AND_ASSIGN(SetCanonicalCookieTask);
728 };
729
730 void CookieMonster::SetCanonicalCookieTask::Run() {
731 bool result = this->cookie_monster()->SetCanonicalCookie(
732 std::move(cookie_), secure_source_, modify_http_only_);
733 if (!callback_.is_null())
734 std::move(callback_).Run(result);
735 }
736
737 // Task class for SetCookieWithOptions call.
738 class CookieMonster::SetCookieWithOptionsTask : public CookieMonsterTask {
739 public:
740 SetCookieWithOptionsTask(CookieMonster* cookie_monster,
741 const GURL& url,
742 const std::string& cookie_line,
743 const CookieOptions& options,
744 SetCookiesCallback callback)
745 : CookieMonsterTask(cookie_monster),
746 url_(url),
747 cookie_line_(cookie_line),
748 options_(options),
749 callback_(std::move(callback)) {}
750
751 // CookieMonsterTask:
752 void Run() override;
753
754 protected:
755 ~SetCookieWithOptionsTask() override {}
756
757 private:
758 GURL url_;
759 std::string cookie_line_;
760 CookieOptions options_;
761 SetCookiesCallback callback_;
762
763 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask);
764 };
765
766 void CookieMonster::SetCookieWithOptionsTask::Run() {
767 bool result = this->cookie_monster()->SetCookieWithOptions(url_, cookie_line_,
768 options_);
769 if (!callback_.is_null())
770 std::move(callback_).Run(result);
771 }
772
773 // Task class for SetAllCookies call.
774 class CookieMonster::SetAllCookiesTask : public CookieMonsterTask {
775 public:
776 SetAllCookiesTask(CookieMonster* cookie_monster,
777 const CookieList& list,
778 SetCookiesCallback callback)
779 : CookieMonsterTask(cookie_monster),
780 list_(list),
781 callback_(std::move(callback)) {}
782
783 // CookieMonsterTask:
784 void Run() override;
785
786 protected:
787 ~SetAllCookiesTask() override {}
788
789 private:
790 CookieList list_;
791 SetCookiesCallback callback_;
792
793 DISALLOW_COPY_AND_ASSIGN(SetAllCookiesTask);
794 };
795
796 void CookieMonster::SetAllCookiesTask::Run() {
797 CookieList positive_diff;
798 CookieList negative_diff;
799 CookieList old_cookies = this->cookie_monster()->GetAllCookies();
800 this->cookie_monster()->ComputeCookieDiff(&old_cookies, &list_,
801 &positive_diff, &negative_diff);
802
803 for (CookieList::const_iterator it = negative_diff.begin();
804 it != negative_diff.end(); ++it) {
805 this->cookie_monster()->DeleteCanonicalCookie(*it);
806 }
807
808 bool result = true;
809 if (positive_diff.size() > 0)
810 result = this->cookie_monster()->SetAllCookies(list_);
811
812 if (!callback_.is_null())
813 std::move(callback_).Run(result);
814 }
815
816 // Task class for GetCookiesWithOptions call.
817 class CookieMonster::GetCookiesWithOptionsTask : public CookieMonsterTask {
818 public:
819 GetCookiesWithOptionsTask(CookieMonster* cookie_monster,
820 const GURL& url,
821 const CookieOptions& options,
822 GetCookiesCallback callback)
823 : CookieMonsterTask(cookie_monster),
824 url_(url),
825 options_(options),
826 callback_(std::move(callback)) {}
827
828 // CookieMonsterTask:
829 void Run() override;
830
831 protected:
832 ~GetCookiesWithOptionsTask() override {}
833
834 private:
835 GURL url_;
836 CookieOptions options_;
837 GetCookiesCallback callback_;
838
839 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask);
840 };
841
842 void CookieMonster::GetCookiesWithOptionsTask::Run() {
843 std::string cookie =
844 this->cookie_monster()->GetCookiesWithOptions(url_, options_);
845 if (!callback_.is_null())
846 std::move(callback_).Run(cookie);
847 }
848
849 // Task class for DeleteCookie call.
850 class CookieMonster::DeleteCookieTask : public DeleteTask<void> {
851 public:
852 DeleteCookieTask(CookieMonster* cookie_monster,
853 const GURL& url,
854 const std::string& cookie_name,
855 base::OnceClosure callback)
856 : DeleteTask<void>(cookie_monster, std::move(callback)),
857 url_(url),
858 cookie_name_(cookie_name) {}
859
860 // DeleteTask:
861 void RunDeleteTask() override;
862
863 protected:
864 ~DeleteCookieTask() override {}
865
866 private:
867 GURL url_;
868 std::string cookie_name_;
869
870 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask);
871 };
872
873 void CookieMonster::DeleteCookieTask::RunDeleteTask() {
874 this->cookie_monster()->DeleteCookie(url_, cookie_name_);
875 }
876
877 // Task class for DeleteSessionCookies call.
878 class CookieMonster::DeleteSessionCookiesTask : public DeleteTask<uint32_t> {
879 public:
880 DeleteSessionCookiesTask(CookieMonster* cookie_monster,
881 DeleteCallback callback)
882 : DeleteTask<uint32_t>(cookie_monster, std::move(callback)) {}
883
884 // DeleteTask:
885 uint32_t RunDeleteTask() override;
886
887 protected:
888 ~DeleteSessionCookiesTask() override {}
889
890 private:
891 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask);
892 };
893
894 uint32_t CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
895 return this->cookie_monster()->DeleteSessionCookies();
896 }
897
898 // Asynchronous CookieMonster API 413 // Asynchronous CookieMonster API
899 414
900 void CookieMonster::SetCookieWithDetailsAsync(const GURL& url, 415 void CookieMonster::SetCookieWithDetailsAsync(const GURL& url,
901 const std::string& name, 416 const std::string& name,
902 const std::string& value, 417 const std::string& value,
903 const std::string& domain, 418 const std::string& domain,
904 const std::string& path, 419 const std::string& path,
905 Time creation_time, 420 Time creation_time,
906 Time expiration_time, 421 Time expiration_time,
907 Time last_access_time, 422 Time last_access_time,
908 bool secure, 423 bool secure,
909 bool http_only, 424 bool http_only,
910 CookieSameSite same_site, 425 CookieSameSite same_site,
911 CookiePriority priority, 426 CookiePriority priority,
912 SetCookiesCallback callback) { 427 SetCookiesCallback callback) {
913 scoped_refptr<SetCookieWithDetailsTask> task = new SetCookieWithDetailsTask( 428 DoCookieCallbackForURL(
914 this, url, name, value, domain, path, creation_time, expiration_time, 429 base::BindOnce(
915 last_access_time, secure, http_only, same_site, priority, 430 // base::Unretained is safe as DoCookieCallbackForURL stores
916 std::move(callback)); 431 // the callback on |*this|, so the callback will not outlive
917 DoCookieTaskForURL(task, url); 432 // the object.
433 &CookieMonster::SetCookieWithDetails, base::Unretained(this), url,
434 name, value, domain, path, creation_time, expiration_time,
435 last_access_time, secure, http_only, same_site, priority,
436 std::move(callback)),
437 url);
918 } 438 }
919 439
920 void CookieMonster::FlushStore(base::OnceClosure callback) { 440 void CookieMonster::FlushStore(base::OnceClosure callback) {
921 DCHECK(thread_checker_.CalledOnValidThread()); 441 DCHECK(thread_checker_.CalledOnValidThread());
922 442
923 if (initialized_ && store_.get()) { 443 if (initialized_ && store_.get()) {
924 if (channel_id_service_) { 444 if (channel_id_service_) {
925 channel_id_service_->GetChannelIDStore()->Flush(); 445 channel_id_service_->GetChannelIDStore()->Flush();
926 } 446 }
927 store_->Flush(std::move(callback)); 447 store_->Flush(std::move(callback));
928 } else if (!callback.is_null()) { 448 } else if (callback) {
929 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, 449 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
930 std::move(callback)); 450 std::move(callback));
931 } 451 }
932 } 452 }
933 453
934 void CookieMonster::SetForceKeepSessionState() { 454 void CookieMonster::SetForceKeepSessionState() {
935 DCHECK(thread_checker_.CalledOnValidThread()); 455 DCHECK(thread_checker_.CalledOnValidThread());
936 456
937 if (store_) 457 if (store_)
938 store_->SetForceKeepSessionState(); 458 store_->SetForceKeepSessionState();
939 } 459 }
940 460
941 void CookieMonster::SetAllCookiesAsync(const CookieList& list, 461 void CookieMonster::SetAllCookiesAsync(const CookieList& list,
942 SetCookiesCallback callback) { 462 SetCookiesCallback callback) {
943 scoped_refptr<SetAllCookiesTask> task = 463 DoCookieCallback(base::BindOnce(
944 new SetAllCookiesTask(this, list, std::move(callback)); 464 // base::Unretained is safe as DoCookieCallbackForURL stores
945 DoCookieTask(task); 465 // the callback on |*this|, so the callback will not outlive
466 // the object.
467 &CookieMonster::SetAllCookies, base::Unretained(this), list,
468 std::move(callback)));
946 } 469 }
947 470
948 void CookieMonster::SetCanonicalCookieAsync( 471 void CookieMonster::SetCanonicalCookieAsync(
949 std::unique_ptr<CanonicalCookie> cookie, 472 std::unique_ptr<CanonicalCookie> cookie,
950 bool secure_source, 473 bool secure_source,
951 bool modify_http_only, 474 bool modify_http_only,
952 SetCookiesCallback callback) { 475 SetCookiesCallback callback) {
953 DCHECK(cookie->IsCanonical()); 476 DCHECK(cookie->IsCanonical());
954 scoped_refptr<SetCanonicalCookieTask> task =
955 new SetCanonicalCookieTask(this, std::move(cookie), secure_source,
956 modify_http_only, std::move(callback));
957 477
958 // TODO(rdsmith): Switch to DoCookieTaskForURL (or the equivalent). 478 // TODO(rdsmith): Switch to DoCookieCallbackForURL (or the equivalent).
959 // This is tricky because we don't have the scheme in this routine 479 // This is tricky because we don't have the scheme in this routine
960 // and DoCookieTaskForURL uses cookie_util::GetEffectiveDomain(scheme, host) 480 // and DoCookieCallbackForURL uses
481 // cookie_util::GetEffectiveDomain(scheme, host)
961 // to generate the database key to block behind. 482 // to generate the database key to block behind.
962 DoCookieTask(task); 483 DoCookieCallback(base::BindOnce(
484 // base::Unretained is safe as DoCookieCallbackForURL stores
485 // the callback on |*this|, so the callback will not outlive
486 // the object.
487 &CookieMonster::SetCanonicalCookie, base::Unretained(this),
488 std::move(cookie), secure_source, modify_http_only, std::move(callback)));
963 } 489 }
964 490
965 void CookieMonster::SetCookieWithOptionsAsync(const GURL& url, 491 void CookieMonster::SetCookieWithOptionsAsync(const GURL& url,
966 const std::string& cookie_line, 492 const std::string& cookie_line,
967 const CookieOptions& options, 493 const CookieOptions& options,
968 SetCookiesCallback callback) { 494 SetCookiesCallback callback) {
969 scoped_refptr<SetCookieWithOptionsTask> task = new SetCookieWithOptionsTask( 495 DoCookieCallbackForURL(
970 this, url, cookie_line, options, std::move(callback)); 496 base::BindOnce(
971 497 // base::Unretained is safe as DoCookieCallbackForURL stores
972 DoCookieTaskForURL(task, url); 498 // the callback on |*this|, so the callback will not outlive
499 // the object.
500 &CookieMonster::SetCookieWithOptions, base::Unretained(this), url,
501 cookie_line, options, std::move(callback)),
502 url);
973 } 503 }
974 504
975 void CookieMonster::GetCookiesWithOptionsAsync(const GURL& url, 505 void CookieMonster::GetCookiesWithOptionsAsync(const GURL& url,
976 const CookieOptions& options, 506 const CookieOptions& options,
977 GetCookiesCallback callback) { 507 GetCookiesCallback callback) {
978 scoped_refptr<GetCookiesWithOptionsTask> task = 508 DoCookieCallbackForURL(
979 new GetCookiesWithOptionsTask(this, url, options, std::move(callback)); 509 base::BindOnce(
980 510 // base::Unretained is safe as DoCookieCallbackForURL stores
981 DoCookieTaskForURL(task, url); 511 // the callback on |*this|, so the callback will not outlive
512 // the object.
513 &CookieMonster::GetCookiesWithOptions, base::Unretained(this), url,
514 options, std::move(callback)),
515 url);
982 } 516 }
983 517
984 void CookieMonster::GetCookieListWithOptionsAsync( 518 void CookieMonster::GetCookieListWithOptionsAsync(
985 const GURL& url, 519 const GURL& url,
986 const CookieOptions& options, 520 const CookieOptions& options,
987 GetCookieListCallback callback) { 521 GetCookieListCallback callback) {
988 scoped_refptr<GetCookieListWithOptionsTask> task = 522 DoCookieCallbackForURL(
989 new GetCookieListWithOptionsTask(this, url, options, std::move(callback)); 523 base::BindOnce(
990 524 // base::Unretained is safe as DoCookieCallbackForURL stores
991 DoCookieTaskForURL(task, url); 525 // the callback on |*this|, so the callback will not outlive
526 // the object.
527 &CookieMonster::GetCookieListWithOptions, base::Unretained(this), url,
528 options, std::move(callback)),
529 url);
992 } 530 }
993 531
994 void CookieMonster::GetAllCookiesAsync(GetCookieListCallback callback) { 532 void CookieMonster::GetAllCookiesAsync(GetCookieListCallback callback) {
995 scoped_refptr<GetAllCookiesTask> task = 533 DoCookieCallback(base::BindOnce(
996 new GetAllCookiesTask(this, std::move(callback)); 534 // base::Unretained is safe as DoCookieCallbackForURL stores
997 535 // the callback on |*this|, so the callback will not outlive
998 DoCookieTask(task); 536 // the object.
537 &CookieMonster::GetAllCookies, base::Unretained(this),
538 std::move(callback)));
999 } 539 }
1000 540
1001 void CookieMonster::DeleteCookieAsync(const GURL& url, 541 void CookieMonster::DeleteCookieAsync(const GURL& url,
1002 const std::string& cookie_name, 542 const std::string& cookie_name,
1003 base::OnceClosure callback) { 543 base::OnceClosure callback) {
1004 scoped_refptr<DeleteCookieTask> task = 544 DoCookieCallbackForURL(
1005 new DeleteCookieTask(this, url, cookie_name, std::move(callback)); 545 base::BindOnce(
1006 546 // base::Unretained is safe as DoCookieCallbackForURL stores
1007 DoCookieTaskForURL(task, url); 547 // the callback on |*this|, so the callback will not outlive
548 // the object.
549 &CookieMonster::DeleteCookie, base::Unretained(this), url,
550 cookie_name, std::move(callback)),
551 url);
1008 } 552 }
1009 553
1010 void CookieMonster::DeleteCanonicalCookieAsync(const CanonicalCookie& cookie, 554 void CookieMonster::DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
1011 DeleteCallback callback) { 555 DeleteCallback callback) {
1012 scoped_refptr<DeleteCanonicalCookieTask> task = 556 DoCookieCallback(base::BindOnce(
1013 new DeleteCanonicalCookieTask(this, cookie, std::move(callback)); 557 // base::Unretained is safe as DoCookieCallbackForURL stores
1014 558 // the callback on |*this|, so the callback will not outlive
1015 DoCookieTask(task); 559 // the object.
560 &CookieMonster::DeleteCanonicalCookie, base::Unretained(this), cookie,
561 std::move(callback)));
1016 } 562 }
1017 563
1018 void CookieMonster::DeleteAllCreatedBetweenAsync(const Time& delete_begin, 564 void CookieMonster::DeleteAllCreatedBetweenAsync(const Time& delete_begin,
1019 const Time& delete_end, 565 const Time& delete_end,
1020 DeleteCallback callback) { 566 DeleteCallback callback) {
1021 scoped_refptr<DeleteAllCreatedBetweenTask> task = 567 DoCookieCallback(base::BindOnce(
1022 new DeleteAllCreatedBetweenTask(this, delete_begin, delete_end, 568 // base::Unretained is safe as DoCookieCallbackForURL stores
1023 std::move(callback)); 569 // the callback on |*this|, so the callback will not outlive
1024 570 // the object.
1025 DoCookieTask(task); 571 &CookieMonster::DeleteAllCreatedBetween, base::Unretained(this),
572 delete_begin, delete_end, std::move(callback)));
1026 } 573 }
1027 574
1028 void CookieMonster::DeleteAllCreatedBetweenWithPredicateAsync( 575 void CookieMonster::DeleteAllCreatedBetweenWithPredicateAsync(
1029 const Time& delete_begin, 576 const Time& delete_begin,
1030 const Time& delete_end, 577 const Time& delete_end,
1031 const base::Callback<bool(const CanonicalCookie&)>& predicate, 578 const base::Callback<bool(const CanonicalCookie&)>& predicate,
1032 DeleteCallback callback) { 579 DeleteCallback callback) {
1033 if (predicate.is_null()) { 580 if (predicate.is_null()) {
1034 std::move(callback).Run(0); 581 MaybeRunCookieCallback(std::move(callback), 0u);
1035 return; 582 return;
1036 } 583 }
1037 scoped_refptr<DeleteAllCreatedBetweenWithPredicateTask> task = 584
1038 new DeleteAllCreatedBetweenWithPredicateTask( 585 DoCookieCallback(base::BindOnce(
1039 this, delete_begin, delete_end, predicate, std::move(callback)); 586 // base::Unretained is safe as DoCookieCallbackForURL stores
1040 DoCookieTask(task); 587 // the callback on |*this|, so the callback will not outlive
588 // the object.
589 &CookieMonster::DeleteAllCreatedBetweenWithPredicate,
590 base::Unretained(this), delete_begin, delete_end, predicate,
591 std::move(callback)));
1041 } 592 }
1042 593
1043 void CookieMonster::DeleteSessionCookiesAsync( 594 void CookieMonster::DeleteSessionCookiesAsync(
1044 CookieStore::DeleteCallback callback) { 595 CookieStore::DeleteCallback callback) {
1045 scoped_refptr<DeleteSessionCookiesTask> task = 596 DoCookieCallback(base::BindOnce(
1046 new DeleteSessionCookiesTask(this, std::move(callback)); 597 // base::Unretained is safe as DoCookieCallbackForURL stores
1047 598 // the callback on |*this|, so the callback will not outlive
1048 DoCookieTask(task); 599 // the object.
600 &CookieMonster::DeleteSessionCookies, base::Unretained(this),
601 std::move(callback)));
1049 } 602 }
1050 603
1051 void CookieMonster::SetCookieableSchemes( 604 void CookieMonster::SetCookieableSchemes(
1052 const std::vector<std::string>& schemes) { 605 const std::vector<std::string>& schemes) {
1053 DCHECK(thread_checker_.CalledOnValidThread()); 606 DCHECK(thread_checker_.CalledOnValidThread());
1054 607
1055 // Calls to this method will have no effect if made after a WebView or 608 // Calls to this method will have no effect if made after a WebView or
1056 // CookieManager instance has been created. 609 // CookieManager instance has been created.
1057 if (initialized_) 610 if (initialized_)
1058 return; 611 return;
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
1102 // CookieChanged callbacks when the CookieStore is destroyed? 655 // CookieChanged callbacks when the CookieStore is destroyed?
1103 for (CookieMap::iterator cookie_it = cookies_.begin(); 656 for (CookieMap::iterator cookie_it = cookies_.begin();
1104 cookie_it != cookies_.end();) { 657 cookie_it != cookies_.end();) {
1105 CookieMap::iterator current_cookie_it = cookie_it; 658 CookieMap::iterator current_cookie_it = cookie_it;
1106 ++cookie_it; 659 ++cookie_it;
1107 InternalDeleteCookie(current_cookie_it, false /* sync_to_store */, 660 InternalDeleteCookie(current_cookie_it, false /* sync_to_store */,
1108 DELETE_COOKIE_DONT_RECORD); 661 DELETE_COOKIE_DONT_RECORD);
1109 } 662 }
1110 } 663 }
1111 664
1112 bool CookieMonster::SetCookieWithDetails(const GURL& url, 665 void CookieMonster::SetCookieWithDetails(const GURL& url,
1113 const std::string& name, 666 const std::string& name,
1114 const std::string& value, 667 const std::string& value,
1115 const std::string& domain, 668 const std::string& domain,
1116 const std::string& path, 669 const std::string& path,
1117 base::Time creation_time, 670 base::Time creation_time,
1118 base::Time expiration_time, 671 base::Time expiration_time,
1119 base::Time last_access_time, 672 base::Time last_access_time,
1120 bool secure, 673 bool secure,
1121 bool http_only, 674 bool http_only,
1122 CookieSameSite same_site, 675 CookieSameSite same_site,
1123 CookiePriority priority) { 676 CookiePriority priority,
677 SetCookiesCallback callback) {
1124 DCHECK(thread_checker_.CalledOnValidThread()); 678 DCHECK(thread_checker_.CalledOnValidThread());
1125 679
1126 if (!HasCookieableScheme(url)) 680 if (!HasCookieableScheme(url)) {
1127 return false; 681 MaybeRunCookieCallback(std::move(callback), false);
682 return;
683 }
1128 684
1129 // Validate consistency of passed arguments. 685 // Validate consistency of passed arguments.
1130 if (ParsedCookie::ParseTokenString(name) != name || 686 if (ParsedCookie::ParseTokenString(name) != name ||
1131 ParsedCookie::ParseValueString(value) != value || 687 ParsedCookie::ParseValueString(value) != value ||
1132 ParsedCookie::ParseValueString(domain) != domain || 688 ParsedCookie::ParseValueString(domain) != domain ||
1133 ParsedCookie::ParseValueString(path) != path) { 689 ParsedCookie::ParseValueString(path) != path) {
1134 return false; 690 MaybeRunCookieCallback(std::move(callback), false);
691 return;
1135 } 692 }
1136 693
1137 std::string cookie_domain; 694 std::string cookie_domain;
1138 if (!cookie_util::GetCookieDomainWithString(url, domain, &cookie_domain)) 695 if (!cookie_util::GetCookieDomainWithString(url, domain, &cookie_domain)) {
1139 return false; 696 MaybeRunCookieCallback(std::move(callback), false);
697 return;
698 }
1140 699
1141 std::string cookie_path = CanonicalCookie::CanonPathWithString(url, path); 700 std::string cookie_path = CanonicalCookie::CanonPathWithString(url, path);
1142 if (!path.empty() && cookie_path != path) 701 if (!path.empty() && cookie_path != path) {
1143 return false; 702 MaybeRunCookieCallback(std::move(callback), false);
703 return;
704 }
1144 705
1145 // Canonicalize path again to make sure it escapes characters as needed. 706 // Canonicalize path again to make sure it escapes characters as needed.
1146 url::Component path_component(0, cookie_path.length()); 707 url::Component path_component(0, cookie_path.length());
1147 url::RawCanonOutputT<char> canon_path; 708 url::RawCanonOutputT<char> canon_path;
1148 url::Component canon_path_component; 709 url::Component canon_path_component;
1149 url::CanonicalizePath(cookie_path.data(), path_component, &canon_path, 710 url::CanonicalizePath(cookie_path.data(), path_component, &canon_path,
1150 &canon_path_component); 711 &canon_path_component);
1151 cookie_path = std::string(canon_path.data() + canon_path_component.begin, 712 cookie_path = std::string(canon_path.data() + canon_path_component.begin,
1152 canon_path_component.len); 713 canon_path_component.len);
1153 714
1154 std::unique_ptr<CanonicalCookie> cc(base::MakeUnique<CanonicalCookie>( 715 std::unique_ptr<CanonicalCookie> cc(base::MakeUnique<CanonicalCookie>(
1155 name, value, cookie_domain, cookie_path, creation_time, expiration_time, 716 name, value, cookie_domain, cookie_path, creation_time, expiration_time,
1156 last_access_time, secure, http_only, same_site, priority)); 717 last_access_time, secure, http_only, same_site, priority));
1157 718
1158 return SetCanonicalCookie(std::move(cc), url.SchemeIsCryptographic(), true); 719 SetCanonicalCookie(std::move(cc), url.SchemeIsCryptographic(), true,
720 std::move(callback));
1159 } 721 }
1160 722
1161 CookieList CookieMonster::GetAllCookies() { 723 void CookieMonster::GetAllCookies(GetCookieListCallback callback) {
1162 DCHECK(thread_checker_.CalledOnValidThread()); 724 DCHECK(thread_checker_.CalledOnValidThread());
1163 725
1164 // This function is being called to scrape the cookie list for management UI 726 // This function is being called to scrape the cookie list for management UI
1165 // or similar. We shouldn't show expired cookies in this list since it will 727 // or similar. We shouldn't show expired cookies in this list since it will
1166 // just be confusing to users, and this function is called rarely enough (and 728 // just be confusing to users, and this function is called rarely enough (and
1167 // is already slow enough) that it's OK to take the time to garbage collect 729 // is already slow enough) that it's OK to take the time to garbage collect
1168 // the expired cookies now. 730 // the expired cookies now.
1169 // 731 //
1170 // Note that this does not prune cookies to be below our limits (if we've 732 // Note that this does not prune cookies to be below our limits (if we've
1171 // exceeded them) the way that calling GarbageCollect() would. 733 // exceeded them) the way that calling GarbageCollect() would.
1172 GarbageCollectExpired( 734 GarbageCollectExpired(
1173 Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), NULL); 735 Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), NULL);
1174 736
1175 // Copy the CanonicalCookie pointers from the map so that we can use the same 737 // Copy the CanonicalCookie pointers from the map so that we can use the same
1176 // sorter as elsewhere, then copy the result out. 738 // sorter as elsewhere, then copy the result out.
1177 std::vector<CanonicalCookie*> cookie_ptrs; 739 std::vector<CanonicalCookie*> cookie_ptrs;
1178 cookie_ptrs.reserve(cookies_.size()); 740 cookie_ptrs.reserve(cookies_.size());
1179 for (const auto& cookie : cookies_) 741 for (const auto& cookie : cookies_)
1180 cookie_ptrs.push_back(cookie.second.get()); 742 cookie_ptrs.push_back(cookie.second.get());
1181 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter); 743 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1182 744
1183 CookieList cookie_list; 745 CookieList cookie_list;
1184 cookie_list.reserve(cookie_ptrs.size()); 746 cookie_list.reserve(cookie_ptrs.size());
1185 for (auto* cookie_ptr : cookie_ptrs) 747 for (auto* cookie_ptr : cookie_ptrs)
1186 cookie_list.push_back(*cookie_ptr); 748 cookie_list.push_back(*cookie_ptr);
1187 749
1188 return cookie_list; 750 MaybeRunCookieCallback(std::move(callback), cookie_list);
1189 } 751 }
1190 752
1191 CookieList CookieMonster::GetCookieListWithOptions( 753 void CookieMonster::GetCookieListWithOptions(const GURL& url,
1192 const GURL& url, 754 const CookieOptions& options,
1193 const CookieOptions& options) { 755 GetCookieListCallback callback) {
1194 DCHECK(thread_checker_.CalledOnValidThread()); 756 DCHECK(thread_checker_.CalledOnValidThread());
1195 757
1196 CookieList cookies; 758 CookieList cookies;
1197 if (!HasCookieableScheme(url)) 759 if (HasCookieableScheme(url)) {
1198 return cookies; 760 std::vector<CanonicalCookie*> cookie_ptrs;
761 FindCookiesForHostAndDomain(url, options, &cookie_ptrs);
762 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
1199 763
1200 std::vector<CanonicalCookie*> cookie_ptrs; 764 cookies.reserve(cookie_ptrs.size());
1201 FindCookiesForHostAndDomain(url, options, &cookie_ptrs); 765 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin();
1202 std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter); 766 it != cookie_ptrs.end(); it++)
1203 767 cookies.push_back(**it);
1204 cookies.reserve(cookie_ptrs.size()); 768 }
1205 for (std::vector<CanonicalCookie*>::const_iterator it = cookie_ptrs.begin(); 769 MaybeRunCookieCallback(std::move(callback), cookies);
1206 it != cookie_ptrs.end(); it++)
1207 cookies.push_back(**it);
1208
1209 return cookies;
1210 } 770 }
1211 771
1212 uint32_t CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin, 772 void CookieMonster::DeleteAllCreatedBetween(const Time& delete_begin,
1213 const Time& delete_end) { 773 const Time& delete_end,
774 DeleteCallback callback) {
1214 DCHECK(thread_checker_.CalledOnValidThread()); 775 DCHECK(thread_checker_.CalledOnValidThread());
1215 776
1216 uint32_t num_deleted = 0; 777 uint32_t num_deleted = 0;
1217 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 778 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1218 CookieMap::iterator curit = it; 779 CookieMap::iterator curit = it;
1219 CanonicalCookie* cc = curit->second.get(); 780 CanonicalCookie* cc = curit->second.get();
1220 ++it; 781 ++it;
1221 782
1222 if (cc->CreationDate() >= delete_begin && 783 if (cc->CreationDate() >= delete_begin &&
1223 (delete_end.is_null() || cc->CreationDate() < delete_end)) { 784 (delete_end.is_null() || cc->CreationDate() < delete_end)) {
1224 InternalDeleteCookie(curit, true, /*sync_to_store*/ 785 InternalDeleteCookie(curit, true, /*sync_to_store*/
1225 DELETE_COOKIE_CREATED_BETWEEN); 786 DELETE_COOKIE_CREATED_BETWEEN);
1226 ++num_deleted; 787 ++num_deleted;
1227 } 788 }
1228 } 789 }
1229 790
1230 return num_deleted; 791 FlushStore(
792 base::BindOnce(&MayeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
793 callback ? base::BindOnce(std::move(callback), num_deleted)
794 : base::OnceClosure()));
1231 } 795 }
1232 796
1233 uint32_t CookieMonster::DeleteAllCreatedBetweenWithPredicate( 797 void CookieMonster::DeleteAllCreatedBetweenWithPredicate(
1234 const base::Time& delete_begin, 798 const base::Time& delete_begin,
1235 const base::Time& delete_end, 799 const base::Time& delete_end,
1236 const base::Callback<bool(const CanonicalCookie&)>& predicate) { 800 const base::Callback<bool(const CanonicalCookie&)>& predicate,
801 DeleteCallback callback) {
1237 uint32_t num_deleted = 0; 802 uint32_t num_deleted = 0;
1238 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 803 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1239 CookieMap::iterator curit = it; 804 CookieMap::iterator curit = it;
1240 CanonicalCookie* cc = curit->second.get(); 805 CanonicalCookie* cc = curit->second.get();
1241 ++it; 806 ++it;
1242 807
1243 if (cc->CreationDate() >= delete_begin && 808 if (cc->CreationDate() >= delete_begin &&
1244 // The assumption that null |delete_end| is equivalent to 809 // The assumption that null |delete_end| is equivalent to
1245 // Time::Max() is confusing. 810 // Time::Max() is confusing.
1246 (delete_end.is_null() || cc->CreationDate() < delete_end) && 811 (delete_end.is_null() || cc->CreationDate() < delete_end) &&
1247 predicate.Run(*cc)) { 812 predicate.Run(*cc)) {
1248 InternalDeleteCookie(curit, true, /*sync_to_store*/ 813 InternalDeleteCookie(curit, true, /*sync_to_store*/
1249 DELETE_COOKIE_CREATED_BETWEEN_WITH_PREDICATE); 814 DELETE_COOKIE_CREATED_BETWEEN_WITH_PREDICATE);
1250 ++num_deleted; 815 ++num_deleted;
1251 } 816 }
1252 } 817 }
1253 818
1254 return num_deleted; 819 FlushStore(
820 base::BindOnce(&MayeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
821 callback ? base::BindOnce(std::move(callback), num_deleted)
822 : base::OnceClosure()));
1255 } 823 }
1256 824
1257 bool CookieMonster::SetCookieWithOptions(const GURL& url, 825 void CookieMonster::SetCookieWithOptions(const GURL& url,
1258 const std::string& cookie_line, 826 const std::string& cookie_line,
1259 const CookieOptions& options) { 827 const CookieOptions& options,
828 SetCookiesCallback callback) {
1260 DCHECK(thread_checker_.CalledOnValidThread()); 829 DCHECK(thread_checker_.CalledOnValidThread());
1261 830
1262 if (!HasCookieableScheme(url)) { 831 if (!HasCookieableScheme(url)) {
1263 return false; 832 MaybeRunCookieCallback(std::move(callback), false);
833 return;
1264 } 834 }
1265 835
1266 return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options); 836 SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options,
837 std::move(callback));
1267 } 838 }
1268 839
1269 std::string CookieMonster::GetCookiesWithOptions(const GURL& url, 840 void CookieMonster::GetCookiesWithOptions(const GURL& url,
1270 const CookieOptions& options) { 841 const CookieOptions& options,
842 GetCookiesCallback callback) {
1271 DCHECK(thread_checker_.CalledOnValidThread()); 843 DCHECK(thread_checker_.CalledOnValidThread());
1272 844
1273 if (!HasCookieableScheme(url)) 845 std::string cookie_line;
1274 return std::string(); 846 if (HasCookieableScheme(url)) {
847 std::vector<CanonicalCookie*> cookies;
848 FindCookiesForHostAndDomain(url, options, &cookies);
849 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1275 850
1276 std::vector<CanonicalCookie*> cookies; 851 cookie_line = BuildCookieLine(cookies);
1277 FindCookiesForHostAndDomain(url, options, &cookies);
1278 std::sort(cookies.begin(), cookies.end(), CookieSorter);
1279 852
1280 std::string cookie_line = BuildCookieLine(cookies); 853 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
1281 854 }
1282 VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line; 855 MaybeRunCookieCallback(std::move(callback), cookie_line);
1283
1284 return cookie_line;
1285 } 856 }
1286 857
1287 void CookieMonster::DeleteCookie(const GURL& url, 858 void CookieMonster::DeleteCookie(const GURL& url,
1288 const std::string& cookie_name) { 859 const std::string& cookie_name,
860 base::OnceClosure callback) {
1289 DCHECK(thread_checker_.CalledOnValidThread()); 861 DCHECK(thread_checker_.CalledOnValidThread());
1290 862
1291 if (!HasCookieableScheme(url)) 863 if (!HasCookieableScheme(url)) {
864 // TODO(rdsmith): Would be good to provide a failure indication here.
865 MaybeRunCookieCallback(std::move(callback));
1292 return; 866 return;
867 }
1293 868
1294 CookieOptions options; 869 CookieOptions options;
1295 options.set_include_httponly(); 870 options.set_include_httponly();
1296 options.set_same_site_cookie_mode( 871 options.set_same_site_cookie_mode(
1297 CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); 872 CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
1298 // Get the cookies for this host and its domain(s). 873 // Get the cookies for this host and its domain(s).
1299 std::vector<CanonicalCookie*> cookies; 874 std::vector<CanonicalCookie*> cookies;
1300 FindCookiesForHostAndDomain(url, options, &cookies); 875 FindCookiesForHostAndDomain(url, options, &cookies);
1301 std::set<CanonicalCookie*> matching_cookies; 876 std::set<CanonicalCookie*> matching_cookies;
1302 877
1303 for (auto* cookie : cookies) { 878 for (auto* cookie : cookies) {
1304 if (cookie->Name() != cookie_name) 879 if (cookie->Name() != cookie_name)
1305 continue; 880 continue;
1306 if (!cookie->IsOnPath(url.path())) 881 if (!cookie->IsOnPath(url.path()))
1307 continue; 882 continue;
1308 matching_cookies.insert(cookie); 883 matching_cookies.insert(cookie);
1309 } 884 }
1310 885
1311 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 886 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1312 CookieMap::iterator curit = it; 887 CookieMap::iterator curit = it;
1313 ++it; 888 ++it;
1314 if (matching_cookies.find(curit->second.get()) != matching_cookies.end()) { 889 if (matching_cookies.find(curit->second.get()) != matching_cookies.end()) {
1315 InternalDeleteCookie(curit, true, DELETE_COOKIE_SINGLE); 890 InternalDeleteCookie(curit, true, DELETE_COOKIE_SINGLE);
1316 } 891 }
1317 } 892 }
893
894 FlushStore(base::BindOnce(&MayeRunDeleteCallback,
895 weak_ptr_factory_.GetWeakPtr(),
896 // No callback null check needed as BindOnce
897 // is not being called and MaybeRunDeleteCallback
898 // has its own check.
899 std::move(callback)));
1318 } 900 }
1319 901
1320 uint32_t CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie) { 902 void CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie,
903 DeleteCallback callback) {
1321 DCHECK(thread_checker_.CalledOnValidThread()); 904 DCHECK(thread_checker_.CalledOnValidThread());
1322 905
906 uint32_t result = 0u;
1323 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain())); 907 for (CookieMapItPair its = cookies_.equal_range(GetKey(cookie.Domain()));
1324 its.first != its.second; ++its.first) { 908 its.first != its.second; ++its.first) {
1325 // The creation date acts as the unique index... 909 // The creation date acts as the unique index...
1326 if (its.first->second->CreationDate() == cookie.CreationDate()) { 910 if (its.first->second->CreationDate() == cookie.CreationDate()) {
1327 InternalDeleteCookie(its.first, true, DELETE_COOKIE_CANONICAL); 911 InternalDeleteCookie(its.first, true, DELETE_COOKIE_CANONICAL);
1328 return 1u; 912 result = 1u;
913 break;
1329 } 914 }
1330 } 915 }
1331 return 0u; 916 FlushStore(
917 base::BindOnce(&MayeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
918 callback ? base::BindOnce(std::move(callback), result)
919 : base::OnceClosure()));
1332 } 920 }
1333 921
1334 bool CookieMonster::SetCookieWithCreationTime(const GURL& url, 922 void CookieMonster::SetCookieWithCreationTimeForTesting(
1335 const std::string& cookie_line, 923 const GURL& url,
1336 const base::Time& creation_time) { 924 const std::string& cookie_line,
925 const base::Time& creation_time,
926 SetCookiesCallback callback) {
1337 DCHECK(thread_checker_.CalledOnValidThread()); 927 DCHECK(thread_checker_.CalledOnValidThread());
1338 DCHECK(!store_.get()) << "This method is only to be used by unit-tests."; 928 DCHECK(!store_.get()) << "This method is only to be used by unit-tests.";
1339 929
1340 if (!HasCookieableScheme(url)) { 930 if (!HasCookieableScheme(url)) {
1341 return false; 931 MaybeRunCookieCallback(std::move(callback), false);
932 return;
1342 } 933 }
1343 934
1344 MarkCookieStoreAsInitialized(); 935 MarkCookieStoreAsInitialized();
1345 if (ShouldFetchAllCookiesWhenFetchingAnyCookie()) 936 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
1346 FetchAllCookiesIfNecessary(); 937 FetchAllCookiesIfNecessary();
1347 938
1348 return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time, 939 return SetCookieWithCreationTimeAndOptions(
1349 CookieOptions()); 940 url, cookie_line, creation_time, CookieOptions(), std::move(callback));
1350 } 941 }
1351 942
1352 uint32_t CookieMonster::DeleteSessionCookies() { 943 void CookieMonster::DeleteSessionCookies(DeleteCallback callback) {
1353 DCHECK(thread_checker_.CalledOnValidThread()); 944 DCHECK(thread_checker_.CalledOnValidThread());
1354 945
1355 uint32_t num_deleted = 0; 946 uint32_t num_deleted = 0;
1356 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) { 947 for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
1357 CookieMap::iterator curit = it; 948 CookieMap::iterator curit = it;
1358 CanonicalCookie* cc = curit->second.get(); 949 CanonicalCookie* cc = curit->second.get();
1359 ++it; 950 ++it;
1360 951
1361 if (!cc->IsPersistent()) { 952 if (!cc->IsPersistent()) {
1362 InternalDeleteCookie(curit, true, /*sync_to_store*/ 953 InternalDeleteCookie(curit, true, /*sync_to_store*/
1363 DELETE_COOKIE_EXPIRED); 954 DELETE_COOKIE_EXPIRED);
1364 ++num_deleted; 955 ++num_deleted;
1365 } 956 }
1366 } 957 }
1367 958
1368 return num_deleted; 959 FlushStore(
960 base::BindOnce(&MayeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
961 callback ? base::BindOnce(std::move(callback), num_deleted)
962 : base::OnceClosure()));
1369 } 963 }
1370 964
1371 void CookieMonster::MarkCookieStoreAsInitialized() { 965 void CookieMonster::MarkCookieStoreAsInitialized() {
1372 DCHECK(thread_checker_.CalledOnValidThread()); 966 DCHECK(thread_checker_.CalledOnValidThread());
1373 initialized_ = true; 967 initialized_ = true;
1374 } 968 }
1375 969
1376 void CookieMonster::FetchAllCookiesIfNecessary() { 970 void CookieMonster::FetchAllCookiesIfNecessary() {
1377 DCHECK(thread_checker_.CalledOnValidThread()); 971 DCHECK(thread_checker_.CalledOnValidThread());
1378 if (store_.get() && !started_fetching_all_cookies_) { 972 if (store_.get() && !started_fetching_all_cookies_) {
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
1433 1027
1434 auto tasks_pending_for_key = tasks_pending_for_key_.find(key); 1028 auto tasks_pending_for_key = tasks_pending_for_key_.find(key);
1435 1029
1436 // TODO(mmenke): Can this be turned into a DCHECK? 1030 // TODO(mmenke): Can this be turned into a DCHECK?
1437 if (tasks_pending_for_key == tasks_pending_for_key_.end()) 1031 if (tasks_pending_for_key == tasks_pending_for_key_.end())
1438 return; 1032 return;
1439 1033
1440 // Run all tasks for the key. Note that running a task can result in multiple 1034 // Run all tasks for the key. Note that running a task can result in multiple
1441 // tasks being added to the back of the deque. 1035 // tasks being added to the back of the deque.
1442 while (!tasks_pending_for_key->second.empty()) { 1036 while (!tasks_pending_for_key->second.empty()) {
1443 scoped_refptr<CookieMonsterTask> task = 1037 base::OnceClosure task = std::move(tasks_pending_for_key->second.front());
1444 tasks_pending_for_key->second.front();
1445 tasks_pending_for_key->second.pop_front(); 1038 tasks_pending_for_key->second.pop_front();
1446 1039 std::move(task).Run();
1447 task->Run();
1448 } 1040 }
1449 1041
1450 tasks_pending_for_key_.erase(tasks_pending_for_key); 1042 tasks_pending_for_key_.erase(tasks_pending_for_key);
1451 1043
1452 // This has to be done last, in case running a task queues a new task for the 1044 // This has to be done last, in case running a task queues a new task for the
1453 // key, to ensure tasks are run in the correct order. 1045 // key, to ensure tasks are run in the correct order.
1454 keys_loaded_.insert(key); 1046 keys_loaded_.insert(key);
1455 } 1047 }
1456 1048
1457 void CookieMonster::StoreLoadedCookies( 1049 void CookieMonster::StoreLoadedCookies(
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
1517 void CookieMonster::InvokeQueue() { 1109 void CookieMonster::InvokeQueue() {
1518 DCHECK(thread_checker_.CalledOnValidThread()); 1110 DCHECK(thread_checker_.CalledOnValidThread());
1519 1111
1520 // Move all per-key tasks into the global queue, if there are any. This is 1112 // Move all per-key tasks into the global queue, if there are any. This is
1521 // protection about a race where the store learns about all cookies loading 1113 // protection about a race where the store learns about all cookies loading
1522 // before it learned about the cookies for a key loading. 1114 // before it learned about the cookies for a key loading.
1523 1115
1524 // Needed to prevent any recursively queued tasks from going back into the 1116 // Needed to prevent any recursively queued tasks from going back into the
1525 // per-key queues. 1117 // per-key queues.
1526 seen_global_task_ = true; 1118 seen_global_task_ = true;
1527 for (const auto& tasks_for_key : tasks_pending_for_key_) { 1119 for (auto& tasks_for_key : tasks_pending_for_key_) {
1528 tasks_pending_.insert(tasks_pending_.begin(), tasks_for_key.second.begin(), 1120 tasks_pending_.insert(tasks_pending_.begin(),
1529 tasks_for_key.second.end()); 1121 std::make_move_iterator(tasks_for_key.second.begin()),
1122 std::make_move_iterator(tasks_for_key.second.end()));
1530 } 1123 }
1531 tasks_pending_for_key_.clear(); 1124 tasks_pending_for_key_.clear();
1532 1125
1533 while (!tasks_pending_.empty()) { 1126 while (!tasks_pending_.empty()) {
1534 scoped_refptr<CookieMonsterTask> request_task = tasks_pending_.front(); 1127 base::OnceClosure request_task = std::move(tasks_pending_.front());
1535 tasks_pending_.pop_front(); 1128 tasks_pending_.pop_front();
1536 request_task->Run(); 1129 std::move(request_task).Run();
1537 } 1130 }
1538 1131
1539 DCHECK(tasks_pending_for_key_.empty()); 1132 DCHECK(tasks_pending_for_key_.empty());
1540 1133
1541 finished_fetching_all_cookies_ = true; 1134 finished_fetching_all_cookies_ = true;
1542 creation_times_.clear(); 1135 creation_times_.clear();
1543 keys_loaded_.clear(); 1136 keys_loaded_.clear();
1544 } 1137 }
1545 1138
1546 void CookieMonster::EnsureCookiesMapIsValid() { 1139 void CookieMonster::EnsureCookiesMapIsValid() {
(...skipping 225 matching lines...) Expand 10 before | Expand all | Expand 10 after
1772 : 0; 1365 : 0;
1773 type_sample |= cc_ptr->IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0; 1366 type_sample |= cc_ptr->IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0;
1774 type_sample |= cc_ptr->IsSecure() ? 1 << COOKIE_TYPE_SECURE : 0; 1367 type_sample |= cc_ptr->IsSecure() ? 1 << COOKIE_TYPE_SECURE : 0;
1775 histogram_cookie_type_->Add(type_sample); 1368 histogram_cookie_type_->Add(type_sample);
1776 1369
1777 RunCookieChangedCallbacks(*cc_ptr, CookieStore::ChangeCause::INSERTED); 1370 RunCookieChangedCallbacks(*cc_ptr, CookieStore::ChangeCause::INSERTED);
1778 1371
1779 return inserted; 1372 return inserted;
1780 } 1373 }
1781 1374
1782 bool CookieMonster::SetCookieWithCreationTimeAndOptions( 1375 void CookieMonster::SetCookieWithCreationTimeAndOptions(
1783 const GURL& url, 1376 const GURL& url,
1784 const std::string& cookie_line, 1377 const std::string& cookie_line,
1785 const Time& creation_time_or_null, 1378 const Time& creation_time_or_null,
1786 const CookieOptions& options) { 1379 const CookieOptions& options,
1380 SetCookiesCallback callback) {
1787 DCHECK(thread_checker_.CalledOnValidThread()); 1381 DCHECK(thread_checker_.CalledOnValidThread());
1788 1382
1789 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line; 1383 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
1790 1384
1791 Time creation_time = creation_time_or_null; 1385 Time creation_time = creation_time_or_null;
1792 if (creation_time.is_null()) { 1386 if (creation_time.is_null()) {
1793 creation_time = CurrentTime(); 1387 creation_time = CurrentTime();
1794 last_time_seen_ = creation_time; 1388 last_time_seen_ = creation_time;
1795 } 1389 }
1796 1390
1797 std::unique_ptr<CanonicalCookie> cc( 1391 std::unique_ptr<CanonicalCookie> cc(
1798 CanonicalCookie::Create(url, cookie_line, creation_time, options)); 1392 CanonicalCookie::Create(url, cookie_line, creation_time, options));
1799 1393
1800 if (!cc.get()) { 1394 if (!cc.get()) {
1801 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie"; 1395 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
1802 return false; 1396 MaybeRunCookieCallback(std::move(callback), false);
1397 return;
1803 } 1398 }
1804 return SetCanonicalCookie(std::move(cc), url.SchemeIsCryptographic(), 1399 SetCanonicalCookie(std::move(cc), url.SchemeIsCryptographic(),
1805 !options.exclude_httponly()); 1400 !options.exclude_httponly(), std::move(callback));
1806 } 1401 }
1807 1402
1808 bool CookieMonster::SetCanonicalCookie(std::unique_ptr<CanonicalCookie> cc, 1403 void CookieMonster::SetCanonicalCookie(std::unique_ptr<CanonicalCookie> cc,
1809 bool secure_source, 1404 bool secure_source,
1810 bool modify_http_only) { 1405 bool modify_http_only,
1406 SetCookiesCallback callback) {
1811 DCHECK(thread_checker_.CalledOnValidThread()); 1407 DCHECK(thread_checker_.CalledOnValidThread());
1812 1408
1813 if (cc->IsSecure() && !secure_source) 1409 if (cc->IsSecure() && !secure_source) {
1814 return false; 1410 MaybeRunCookieCallback(std::move(callback), false);
1411 return;
1412 }
1815 1413
1816 const std::string key(GetKey(cc->Domain())); 1414 const std::string key(GetKey(cc->Domain()));
1817 1415
1818 // TODO(mmenke): This class assumes each cookie to have a unique creation 1416 // TODO(mmenke): This class assumes each cookie to have a unique creation
1819 // time. Allowing the caller to set the creation time violates that 1417 // time. Allowing the caller to set the creation time violates that
1820 // assumption. Worth fixing? Worth noting that time changes between browser 1418 // assumption. Worth fixing? Worth noting that time changes between browser
1821 // restarts can cause the same issue. 1419 // restarts can cause the same issue.
1822 base::Time creation_date = cc->CreationDate(); 1420 base::Time creation_date = cc->CreationDate();
1823 if (creation_date.is_null()) { 1421 if (creation_date.is_null()) {
1824 creation_date = CurrentTime(); 1422 creation_date = CurrentTime();
1825 cc->SetCreationDate(creation_date); 1423 cc->SetCreationDate(creation_date);
1826 last_time_seen_ = creation_date; 1424 last_time_seen_ = creation_date;
1827 } 1425 }
1828 bool already_expired = cc->IsExpired(creation_date); 1426 bool already_expired = cc->IsExpired(creation_date);
1829 1427
1830 if (DeleteAnyEquivalentCookie(key, *cc, secure_source, !modify_http_only, 1428 if (DeleteAnyEquivalentCookie(key, *cc, secure_source, !modify_http_only,
1831 already_expired)) { 1429 already_expired)) {
1832 std::string error; 1430 std::string error;
1833 error = 1431 error =
1834 "SetCookie() not clobbering httponly cookie or secure cookie for " 1432 "SetCookie() not clobbering httponly cookie or secure cookie for "
1835 "insecure scheme"; 1433 "insecure scheme";
1836 1434
1837 VLOG(kVlogSetCookies) << error; 1435 VLOG(kVlogSetCookies) << error;
1838 return false; 1436 MaybeRunCookieCallback(std::move(callback), false);
1437 return;
1839 } 1438 }
1840 1439
1841 VLOG(kVlogSetCookies) << "SetCookie() key: " << key 1440 VLOG(kVlogSetCookies) << "SetCookie() key: " << key
1842 << " cc: " << cc->DebugString(); 1441 << " cc: " << cc->DebugString();
1843 1442
1844 // Realize that we might be setting an expired cookie, and the only point 1443 // Realize that we might be setting an expired cookie, and the only point
1845 // was to delete the cookie which we've already done. 1444 // was to delete the cookie which we've already done.
1846 if (!already_expired) { 1445 if (!already_expired) {
1847 // See InitializeHistograms() for details. 1446 // See InitializeHistograms() for details.
1848 if (cc->IsPersistent()) { 1447 if (cc->IsPersistent()) {
(...skipping 21 matching lines...) Expand all
1870 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie."; 1469 VLOG(kVlogSetCookies) << "SetCookie() not storing already expired cookie.";
1871 } 1470 }
1872 1471
1873 // We assume that hopefully setting a cookie will be less common than 1472 // We assume that hopefully setting a cookie will be less common than
1874 // querying a cookie. Since setting a cookie can put us over our limits, 1473 // querying a cookie. Since setting a cookie can put us over our limits,
1875 // make sure that we garbage collect... We can also make the assumption that 1474 // make sure that we garbage collect... We can also make the assumption that
1876 // if a cookie was set, in the common case it will be used soon after, 1475 // if a cookie was set, in the common case it will be used soon after,
1877 // and we will purge the expired cookies in GetCookies(). 1476 // and we will purge the expired cookies in GetCookies().
1878 GarbageCollect(creation_date, key); 1477 GarbageCollect(creation_date, key);
1879 1478
1880 return true; 1479 MaybeRunCookieCallback(std::move(callback), true);
1881 } 1480 }
1882 1481
1883 bool CookieMonster::SetAllCookies(const CookieList& list) { 1482 void CookieMonster::SetAllCookies(CookieList list,
1483 SetCookiesCallback callback) {
1884 DCHECK(thread_checker_.CalledOnValidThread()); 1484 DCHECK(thread_checker_.CalledOnValidThread());
1485 CookieList positive_diff;
1486 CookieList negative_diff;
1487
1488 CookieList old_cookies;
1489 old_cookies.reserve(cookies_.size());
1490 for (const auto& cookie : cookies_)
1491 old_cookies.push_back(*cookie.second.get());
1492
1493 ComputeCookieDiff(&old_cookies, &list, &positive_diff, &negative_diff);
1494
1495 for (const auto& cookie_to_delete : negative_diff) {
1496 for (CookieMapItPair its =
1497 cookies_.equal_range(GetKey(cookie_to_delete.Domain()));
1498 its.first != its.second; ++its.first) {
1499 // The creation date acts as the unique index...
1500 if (its.first->second->CreationDate() ==
1501 cookie_to_delete.CreationDate()) {
1502 // TODO(rdsmith): DELETE_COOKIE_CANONICAL is incorrect and should
1503 // be changed.
1504 InternalDeleteCookie(its.first, true, DELETE_COOKIE_CANONICAL);
1505 break;
1506 }
1507 }
1508 }
1509
1510 if (positive_diff.size() == 0) {
1511 MaybeRunCookieCallback(std::move(callback), true);
1512 return;
1513 }
1514
1885 for (const auto& cookie : list) { 1515 for (const auto& cookie : list) {
1886 const std::string key(GetKey(cookie.Domain())); 1516 const std::string key(GetKey(cookie.Domain()));
1887 Time creation_time = cookie.CreationDate(); 1517 Time creation_time = cookie.CreationDate();
1888 bool already_expired = cookie.IsExpired(creation_time); 1518 bool already_expired = cookie.IsExpired(creation_time);
1889 1519
1890 bool result = 1520 bool result =
1891 DeleteAnyEquivalentCookie(key, cookie, true, false, already_expired); 1521 DeleteAnyEquivalentCookie(key, cookie, true, false, already_expired);
1892 DCHECK(!result); 1522 DCHECK(!result);
1893 1523
1894 if (already_expired) 1524 if (already_expired)
1895 continue; 1525 continue;
1896 1526
1897 if (cookie.IsPersistent()) { 1527 if (cookie.IsPersistent()) {
1898 histogram_expiration_duration_minutes_->Add( 1528 histogram_expiration_duration_minutes_->Add(
1899 (cookie.ExpiryDate() - creation_time).InMinutes()); 1529 (cookie.ExpiryDate() - creation_time).InMinutes());
1900 } 1530 }
1901 1531
1902 InternalInsertCookie(key, base::MakeUnique<CanonicalCookie>(cookie), true); 1532 InternalInsertCookie(key, base::MakeUnique<CanonicalCookie>(cookie), true);
1903 GarbageCollect(creation_time, key); 1533 GarbageCollect(creation_time, key);
1904 } 1534 }
1905 1535
1906 // TODO(rdsmith): If this function always returns the same value, it 1536 // TODO(rdsmith): If this function always returns the same value, it
1907 // shouldn't have a return value. But it should also be deleted (see 1537 // shouldn't have a return value. But it should also be deleted (see
1908 // https://codereview.chromium.org/2882063002/#msg64), which would 1538 // https://codereview.chromium.org/2882063002/#msg64), which would
1909 // solve the return value problem. 1539 // solve the return value problem.
1910 return true; 1540 MaybeRunCookieCallback(std::move(callback), true);
1911 } 1541 }
1912 1542
1913 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc, 1543 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1914 const Time& current) { 1544 const Time& current) {
1915 DCHECK(thread_checker_.CalledOnValidThread()); 1545 DCHECK(thread_checker_.CalledOnValidThread());
1916 1546
1917 // Based off the Mozilla code. When a cookie has been accessed recently, 1547 // Based off the Mozilla code. When a cookie has been accessed recently,
1918 // don't bother updating its access time again. This reduces the number of 1548 // don't bother updating its access time again. This reduces the number of
1919 // updates we do during pageload, which in turn reduces the chance our storage 1549 // updates we do during pageload, which in turn reduces the chance our storage
1920 // backend will hit its batch thresholds and be forced to update. 1550 // backend will hit its batch thresholds and be forced to update.
(...skipping 442 matching lines...) Expand 10 before | Expand all | Expand 10 after
2363 } 1993 }
2364 1994
2365 // The system resolution is not high enough, so we can have multiple 1995 // The system resolution is not high enough, so we can have multiple
2366 // set cookies that result in the same system time. When this happens, we 1996 // set cookies that result in the same system time. When this happens, we
2367 // increment by one Time unit. Let's hope computers don't get too fast. 1997 // increment by one Time unit. Let's hope computers don't get too fast.
2368 Time CookieMonster::CurrentTime() { 1998 Time CookieMonster::CurrentTime() {
2369 return std::max(Time::Now(), Time::FromInternalValue( 1999 return std::max(Time::Now(), Time::FromInternalValue(
2370 last_time_seen_.ToInternalValue() + 1)); 2000 last_time_seen_.ToInternalValue() + 1));
2371 } 2001 }
2372 2002
2373 void CookieMonster::DoCookieTask( 2003 void CookieMonster::DoCookieCallback(base::OnceClosure callback) {
2374 const scoped_refptr<CookieMonsterTask>& task_item) {
2375 DCHECK(thread_checker_.CalledOnValidThread()); 2004 DCHECK(thread_checker_.CalledOnValidThread());
2376 2005
2377 MarkCookieStoreAsInitialized(); 2006 MarkCookieStoreAsInitialized();
2378 FetchAllCookiesIfNecessary(); 2007 FetchAllCookiesIfNecessary();
2379 seen_global_task_ = true; 2008 seen_global_task_ = true;
2380 2009
2381 if (!finished_fetching_all_cookies_ && store_.get()) { 2010 if (!finished_fetching_all_cookies_ && store_.get()) {
2382 tasks_pending_.push_back(task_item); 2011 tasks_pending_.push_back(std::move(callback));
2383 return; 2012 return;
2384 } 2013 }
2385 2014
2386 task_item->Run(); 2015 std::move(callback).Run();
2387 } 2016 }
2388 2017
2389 void CookieMonster::DoCookieTaskForURL( 2018 void CookieMonster::DoCookieCallbackForURL(base::OnceClosure callback,
2390 const scoped_refptr<CookieMonsterTask>& task_item, 2019 const GURL& url) {
2391 const GURL& url) {
2392 MarkCookieStoreAsInitialized(); 2020 MarkCookieStoreAsInitialized();
2393 if (ShouldFetchAllCookiesWhenFetchingAnyCookie()) 2021 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
2394 FetchAllCookiesIfNecessary(); 2022 FetchAllCookiesIfNecessary();
2395 2023
2396 // If cookies for the requested domain key (eTLD+1) have been loaded from DB 2024 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
2397 // then run the task, otherwise load from DB. 2025 // then run the task, otherwise load from DB.
2398 if (!finished_fetching_all_cookies_ && store_.get()) { 2026 if (!finished_fetching_all_cookies_ && store_.get()) {
2399 // If a global task has been previously seen, queue the task as a global 2027 // If a global task has been previously seen, queue the task as a global
2400 // task. Note that the CookieMonster may be in the middle of executing 2028 // task. Note that the CookieMonster may be in the middle of executing
2401 // the global queue, |tasks_pending_| may be empty, which is why another 2029 // the global queue, |tasks_pending_| may be empty, which is why another
2402 // bool is needed. 2030 // bool is needed.
2403 if (seen_global_task_) { 2031 if (seen_global_task_) {
2404 tasks_pending_.push_back(task_item); 2032 tasks_pending_.push_back(std::move(callback));
2405 return; 2033 return;
2406 } 2034 }
2407 2035
2408 // Checks if the domain key has been loaded. 2036 // Checks if the domain key has been loaded.
2409 std::string key(cookie_util::GetEffectiveDomain(url.scheme(), url.host())); 2037 std::string key(cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
2410 if (keys_loaded_.find(key) == keys_loaded_.end()) { 2038 if (keys_loaded_.find(key) == keys_loaded_.end()) {
2411 std::map<std::string, 2039 std::map<std::string, std::deque<base::OnceClosure>>::iterator it =
2412 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
2413 tasks_pending_for_key_.find(key); 2040 tasks_pending_for_key_.find(key);
2414 if (it == tasks_pending_for_key_.end()) { 2041 if (it == tasks_pending_for_key_.end()) {
2415 store_->LoadCookiesForKey( 2042 store_->LoadCookiesForKey(
2416 key, base::Bind(&CookieMonster::OnKeyLoaded, 2043 key, base::Bind(&CookieMonster::OnKeyLoaded,
2417 weak_ptr_factory_.GetWeakPtr(), key)); 2044 weak_ptr_factory_.GetWeakPtr(), key));
2418 it = tasks_pending_for_key_ 2045 it = tasks_pending_for_key_
2419 .insert(std::make_pair( 2046 .insert(std::make_pair(key, std::deque<base::OnceClosure>()))
2420 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
2421 .first; 2047 .first;
2422 } 2048 }
2423 it->second.push_back(task_item); 2049 it->second.push_back(std::move(callback));
2424 return; 2050 return;
2425 } 2051 }
2426 } 2052 }
2427 2053
2428 task_item->Run(); 2054 std::move(callback).Run();
2429 } 2055 }
2430 2056
2431 void CookieMonster::ComputeCookieDiff(CookieList* old_cookies, 2057 void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2432 CookieList* new_cookies, 2058 CookieList* new_cookies,
2433 CookieList* cookies_to_add, 2059 CookieList* cookies_to_add,
2434 CookieList* cookies_to_delete) { 2060 CookieList* cookies_to_delete) {
2435 DCHECK(thread_checker_.CalledOnValidThread()); 2061 DCHECK(thread_checker_.CalledOnValidThread());
2436 2062
2437 DCHECK(old_cookies); 2063 DCHECK(old_cookies);
2438 DCHECK(new_cookies); 2064 DCHECK(new_cookies);
(...skipping 17 matching lines...) Expand all
2456 PartialDiffCookieSorter); 2082 PartialDiffCookieSorter);
2457 2083
2458 // Select any new cookie for addition (or update) if no old cookie is exactly 2084 // Select any new cookie for addition (or update) if no old cookie is exactly
2459 // equivalent. 2085 // equivalent.
2460 std::set_difference(new_cookies->begin(), new_cookies->end(), 2086 std::set_difference(new_cookies->begin(), new_cookies->end(),
2461 old_cookies->begin(), old_cookies->end(), 2087 old_cookies->begin(), old_cookies->end(),
2462 std::inserter(*cookies_to_add, cookies_to_add->begin()), 2088 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2463 FullDiffCookieSorter); 2089 FullDiffCookieSorter);
2464 } 2090 }
2465 2091
2466 void CookieMonster::RunCallback(base::OnceClosure callback) {
2467 DCHECK(thread_checker_.CalledOnValidThread());
2468 std::move(callback).Run();
2469 }
2470
2471 void CookieMonster::RunCookieChangedCallbacks(const CanonicalCookie& cookie, 2092 void CookieMonster::RunCookieChangedCallbacks(const CanonicalCookie& cookie,
2472 ChangeCause cause) { 2093 ChangeCause cause) {
2473 DCHECK(thread_checker_.CalledOnValidThread()); 2094 DCHECK(thread_checker_.CalledOnValidThread());
2474 2095
2475 CookieOptions opts; 2096 CookieOptions opts;
2476 opts.set_include_httponly(); 2097 opts.set_include_httponly();
2477 opts.set_same_site_cookie_mode( 2098 opts.set_same_site_cookie_mode(
2478 CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); 2099 CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
2479 // Note that the callbacks in hook_map_ are wrapped with RunAsync(), so they 2100 // Note that the callbacks in hook_map_ are wrapped with RunAsync(), so they
2480 // are guaranteed to not take long - they just post a RunAsync task back to 2101 // are guaranteed to not take long - they just post a RunAsync task back to
2481 // the appropriate thread's message loop and return. 2102 // the appropriate thread's message loop and return.
2482 // TODO(mmenke): Consider running these synchronously? 2103 // TODO(mmenke): Consider running these synchronously?
2483 for (CookieChangedHookMap::iterator it = hook_map_.begin(); 2104 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2484 it != hook_map_.end(); ++it) { 2105 it != hook_map_.end(); ++it) {
2485 std::pair<GURL, std::string> key = it->first; 2106 std::pair<GURL, std::string> key = it->first;
2486 if (cookie.IncludeForRequestURL(key.first, opts) && 2107 if (cookie.IncludeForRequestURL(key.first, opts) &&
2487 cookie.Name() == key.second) { 2108 cookie.Name() == key.second) {
2488 it->second->Notify(cookie, cause); 2109 it->second->Notify(cookie, cause);
2489 } 2110 }
2490 } 2111 }
2491 } 2112 }
2492 2113
2493 } // namespace net 2114 } // namespace net
OLDNEW
« no previous file with comments | « net/cookies/cookie_monster.h ('k') | net/cookies/cookie_monster_perftest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698