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

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: merge 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
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();
Mike West 2016/03/01 13:59:28 I'd suggest doing so, but in a separate CL. No nee
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?
Mike West 2016/03/01 13:59:28 I think so. There shouldn't be any case in which w
mmenke 2016/03/01 16:03:45 My CL to re-order things may change that property
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 it multiple
Mike West 2016/03/01 13:59:28 Nit: s/it multiple/in multiple/
mmenke 2016/03/01 16:03:45 Done.
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 // Removing a task from the deque before running it isn't strictly
1400 } 1354 // necessary, but just seems like a good idea.
Mike West 2016/03/01 13:59:28 Nit: I'd drop the comment. I'd agree that it's a g
mmenke 2016/03/01 16:03:45 Done.
1355 scoped_refptr<CookieMonsterTask> task =
1356 tasks_pending_for_key->second.front();
1357 tasks_pending_for_key->second.pop_front();
1358
1359 task->Run();
1401 } 1360 }
1361
1362 tasks_pending_for_key_.erase(tasks_pending_for_key);
1363
1364 // This has to be done last, in case running a task queues a new task for the
1365 // key, to ensure tasks are run in the correct order.
1366 keys_loaded_.insert(key);
1402 } 1367 }
1403 1368
1404 void CookieMonster::StoreLoadedCookies( 1369 void CookieMonster::StoreLoadedCookies(
1405 const std::vector<CanonicalCookie*>& cookies) { 1370 const std::vector<CanonicalCookie*>& cookies) {
1371 DCHECK(thread_checker_.CalledOnValidThread());
1372
1406 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is 1373 // TODO(erikwright): Remove ScopedTracker below once crbug.com/457528 is
1407 // fixed. 1374 // fixed.
1408 tracked_objects::ScopedTracker tracking_profile( 1375 tracked_objects::ScopedTracker tracking_profile(
1409 FROM_HERE_WITH_EXPLICIT_FUNCTION( 1376 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1410 "457528 CookieMonster::StoreLoadedCookies")); 1377 "457528 CookieMonster::StoreLoadedCookies"));
1411 1378
1412 // Initialize the store and sync in any saved persistent cookies. We don't 1379 // 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, 1380 // removed, and sync'd.
1414 // and sync'd.
1415 base::AutoLock autolock(lock_);
Mike West 2016/03/01 13:59:28 Appropos of nothing, I really like seeing all thes
1416
1417 CookieItVector cookies_with_control_chars; 1381 CookieItVector cookies_with_control_chars;
1418 1382
1419 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin(); 1383 for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin();
1420 it != cookies.end(); ++it) { 1384 it != cookies.end(); ++it) {
1421 int64_t cookie_creation_time = (*it)->CreationDate().ToInternalValue(); 1385 int64_t cookie_creation_time = (*it)->CreationDate().ToInternalValue();
1422 1386
1423 if (creation_times_.insert(cookie_creation_time).second) { 1387 if (creation_times_.insert(cookie_creation_time).second) {
1424 CookieMap::iterator inserted = 1388 CookieMap::iterator inserted =
1425 InternalInsertCookie(GetKey((*it)->Domain()), *it, false); 1389 InternalInsertCookie(GetKey((*it)->Domain()), *it, false);
1426 const Time cookie_access_time((*it)->LastAccessDate()); 1390 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. 1423 // none of our other constraints are violated.
1460 // In particular, the backing store might have given us duplicate cookies. 1424 // In particular, the backing store might have given us duplicate cookies.
1461 1425
1462 // This method could be called multiple times due to priority loading, thus 1426 // 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 1427 // 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. 1428 // since they are expected to be much fewer than total DB.
1465 EnsureCookiesMapIsValid(); 1429 EnsureCookiesMapIsValid();
1466 } 1430 }
1467 1431
1468 void CookieMonster::InvokeQueue() { 1432 void CookieMonster::InvokeQueue() {
1469 while (true) { 1433 DCHECK(thread_checker_.CalledOnValidThread());
1470 scoped_refptr<CookieMonsterTask> request_task; 1434
1471 { 1435 while (!tasks_pending_.empty()) {
1472 base::AutoLock autolock(lock_); 1436 scoped_refptr<CookieMonsterTask> request_task = tasks_pending_.front();
1473 if (tasks_pending_.empty()) { 1437 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(); 1438 request_task->Run();
1483 } 1439 }
1440
1441 finished_fetching_all_cookies_ = true;
1442 creation_times_.clear();
1443 keys_loaded_.clear();
1484 } 1444 }
1485 1445
1486 void CookieMonster::EnsureCookiesMapIsValid() { 1446 void CookieMonster::EnsureCookiesMapIsValid() {
1487 lock_.AssertAcquired(); 1447 DCHECK(thread_checker_.CalledOnValidThread());
1488 1448
1489 // Iterate through all the of the cookies, grouped by host. 1449 // Iterate through all the of the cookies, grouped by host.
1490 CookieMap::iterator prev_range_end = cookies_.begin(); 1450 CookieMap::iterator prev_range_end = cookies_.begin();
1491 while (prev_range_end != cookies_.end()) { 1451 while (prev_range_end != cookies_.end()) {
1492 CookieMap::iterator cur_range_begin = prev_range_end; 1452 CookieMap::iterator cur_range_begin = prev_range_end;
1493 const std::string key = cur_range_begin->first; // Keep a copy. 1453 const std::string key = cur_range_begin->first; // Keep a copy.
1494 CookieMap::iterator cur_range_end = cookies_.upper_bound(key); 1454 CookieMap::iterator cur_range_end = cookies_.upper_bound(key);
1495 prev_range_end = cur_range_end; 1455 prev_range_end = cur_range_end;
1496 1456
1497 // Ensure no equivalent cookies for this host. 1457 // Ensure no equivalent cookies for this host.
1498 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end); 1458 TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end);
1499 } 1459 }
1500 } 1460 }
1501 1461
1502 void CookieMonster::TrimDuplicateCookiesForKey(const std::string& key, 1462 void CookieMonster::TrimDuplicateCookiesForKey(const std::string& key,
1503 CookieMap::iterator begin, 1463 CookieMap::iterator begin,
1504 CookieMap::iterator end) { 1464 CookieMap::iterator end) {
1505 lock_.AssertAcquired(); 1465 DCHECK(thread_checker_.CalledOnValidThread());
1506 1466
1507 // Set of cookies ordered by creation time. 1467 // Set of cookies ordered by creation time.
1508 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet; 1468 typedef std::set<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
1509 1469
1510 // Helper map we populate to find the duplicates. 1470 // Helper map we populate to find the duplicates.
1511 typedef std::map<CookieSignature, CookieSet> EquivalenceMap; 1471 typedef std::map<CookieSignature, CookieSet> EquivalenceMap;
1512 EquivalenceMap equivalent_cookies; 1472 EquivalenceMap equivalent_cookies;
1513 1473
1514 // The number of duplicate cookies that have been found. 1474 // The number of duplicate cookies that have been found.
1515 int num_duplicates = 0; 1475 int num_duplicates = 0;
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
1571 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE); 1531 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
1572 } 1532 }
1573 } 1533 }
1574 DCHECK_EQ(num_duplicates, num_duplicates_found); 1534 DCHECK_EQ(num_duplicates, num_duplicates_found);
1575 } 1535 }
1576 1536
1577 void CookieMonster::FindCookiesForHostAndDomain( 1537 void CookieMonster::FindCookiesForHostAndDomain(
1578 const GURL& url, 1538 const GURL& url,
1579 const CookieOptions& options, 1539 const CookieOptions& options,
1580 std::vector<CanonicalCookie*>* cookies) { 1540 std::vector<CanonicalCookie*>* cookies) {
1581 lock_.AssertAcquired(); 1541 DCHECK(thread_checker_.CalledOnValidThread());
1582 1542
1583 const Time current_time(CurrentTime()); 1543 const Time current_time(CurrentTime());
1584 1544
1585 // Probe to save statistics relatively frequently. We do it here rather 1545 // 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 1546 // 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. 1547 // want to collect statistics whenever the browser's being used.
1588 RecordPeriodicStats(current_time); 1548 RecordPeriodicStats(current_time);
1589 1549
1590 // Can just dispatch to FindCookiesForKey 1550 // Can just dispatch to FindCookiesForKey
1591 const std::string key(GetKey(url.host())); 1551 const std::string key(GetKey(url.host()));
1592 FindCookiesForKey(key, url, options, current_time, cookies); 1552 FindCookiesForKey(key, url, options, current_time, cookies);
1593 } 1553 }
1594 1554
1595 void CookieMonster::FindCookiesForKey(const std::string& key, 1555 void CookieMonster::FindCookiesForKey(const std::string& key,
1596 const GURL& url, 1556 const GURL& url,
1597 const CookieOptions& options, 1557 const CookieOptions& options,
1598 const Time& current, 1558 const Time& current,
1599 std::vector<CanonicalCookie*>* cookies) { 1559 std::vector<CanonicalCookie*>* cookies) {
1600 lock_.AssertAcquired(); 1560 DCHECK(thread_checker_.CalledOnValidThread());
1601 1561
1602 for (CookieMapItPair its = cookies_.equal_range(key); 1562 for (CookieMapItPair its = cookies_.equal_range(key);
1603 its.first != its.second;) { 1563 its.first != its.second;) {
1604 CookieMap::iterator curit = its.first; 1564 CookieMap::iterator curit = its.first;
1605 CanonicalCookie* cc = curit->second; 1565 CanonicalCookie* cc = curit->second;
1606 ++its.first; 1566 ++its.first;
1607 1567
1608 // If the cookie is expired, delete it. 1568 // If the cookie is expired, delete it.
1609 if (cc->IsExpired(current)) { 1569 if (cc->IsExpired(current)) {
1610 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED); 1570 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
(...skipping 13 matching lines...) Expand all
1624 } 1584 }
1625 cookies->push_back(cc); 1585 cookies->push_back(cc);
1626 } 1586 }
1627 } 1587 }
1628 1588
1629 bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key, 1589 bool CookieMonster::DeleteAnyEquivalentCookie(const std::string& key,
1630 const CanonicalCookie& ecc, 1590 const CanonicalCookie& ecc,
1631 bool skip_httponly, 1591 bool skip_httponly,
1632 bool already_expired, 1592 bool already_expired,
1633 bool enforce_strict_secure) { 1593 bool enforce_strict_secure) {
1634 lock_.AssertAcquired(); 1594 DCHECK(thread_checker_.CalledOnValidThread());
1635 1595
1636 bool found_equivalent_cookie = false; 1596 bool found_equivalent_cookie = false;
1637 bool skipped_httponly = false; 1597 bool skipped_httponly = false;
1638 bool skipped_secure_cookie = false; 1598 bool skipped_secure_cookie = false;
1639 1599
1640 histogram_cookie_delete_equivalent_->Add(COOKIE_DELETE_EQUIVALENT_ATTEMPT); 1600 histogram_cookie_delete_equivalent_->Add(COOKIE_DELETE_EQUIVALENT_ATTEMPT);
1641 1601
1642 for (CookieMapItPair its = cookies_.equal_range(key); 1602 for (CookieMapItPair its = cookies_.equal_range(key);
1643 its.first != its.second;) { 1603 its.first != its.second;) {
1644 CookieMap::iterator curit = its.first; 1604 CookieMap::iterator curit = its.first;
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
1687 found_equivalent_cookie = true; 1647 found_equivalent_cookie = true;
1688 } 1648 }
1689 } 1649 }
1690 return skipped_httponly || skipped_secure_cookie; 1650 return skipped_httponly || skipped_secure_cookie;
1691 } 1651 }
1692 1652
1693 CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie( 1653 CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
1694 const std::string& key, 1654 const std::string& key,
1695 CanonicalCookie* cc, 1655 CanonicalCookie* cc,
1696 bool sync_to_store) { 1656 bool sync_to_store) {
1657 DCHECK(thread_checker_.CalledOnValidThread());
1658
1697 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed. 1659 // TODO(mkwst): Remove ScopedTracker below once crbug.com/456373 is fixed.
1698 tracked_objects::ScopedTracker tracking_profile( 1660 tracked_objects::ScopedTracker tracking_profile(
1699 FROM_HERE_WITH_EXPLICIT_FUNCTION( 1661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1700 "456373 CookieMonster::InternalInsertCookie")); 1662 "456373 CookieMonster::InternalInsertCookie"));
1701 lock_.AssertAcquired();
1702 1663
1703 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() && 1664 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1704 sync_to_store) 1665 sync_to_store)
1705 store_->AddCookie(*cc); 1666 store_->AddCookie(*cc);
1706 CookieMap::iterator inserted = 1667 CookieMap::iterator inserted =
1707 cookies_.insert(CookieMap::value_type(key, cc)); 1668 cookies_.insert(CookieMap::value_type(key, cc));
1708 if (delegate_.get()) { 1669 if (delegate_.get()) {
1709 delegate_->OnCookieChanged(*cc, false, 1670 delegate_->OnCookieChanged(*cc, false,
1710 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT); 1671 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT);
1711 } 1672 }
(...skipping 17 matching lines...) Expand all
1729 : COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME; 1690 : COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME;
1730 } else { 1691 } else {
1731 cookie_source_sample = 1692 cookie_source_sample =
1732 cc->IsSecure() 1693 cc->IsSecure()
1733 ? COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME 1694 ? COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME
1734 : COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME; 1695 : COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME;
1735 } 1696 }
1736 histogram_cookie_source_scheme_->Add(cookie_source_sample); 1697 histogram_cookie_source_scheme_->Add(cookie_source_sample);
1737 } 1698 }
1738 1699
1739 RunCallbacks(*cc, false); 1700 RunCookieChangedCallbacks(*cc, false);
1740 1701
1741 return inserted; 1702 return inserted;
1742 } 1703 }
1743 1704
1744 bool CookieMonster::SetCookieWithCreationTimeAndOptions( 1705 bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1745 const GURL& url, 1706 const GURL& url,
1746 const std::string& cookie_line, 1707 const std::string& cookie_line,
1747 const Time& creation_time_or_null, 1708 const Time& creation_time_or_null,
1748 const CookieOptions& options) { 1709 const CookieOptions& options) {
1749 lock_.AssertAcquired(); 1710 DCHECK(thread_checker_.CalledOnValidThread());
1750 1711
1751 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line; 1712 VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
1752 1713
1753 Time creation_time = creation_time_or_null; 1714 Time creation_time = creation_time_or_null;
1754 if (creation_time.is_null()) { 1715 if (creation_time.is_null()) {
1755 creation_time = CurrentTime(); 1716 creation_time = CurrentTime();
1756 last_time_seen_ = creation_time; 1717 last_time_seen_ = creation_time;
1757 } 1718 }
1758 1719
1759 scoped_ptr<CanonicalCookie> cc( 1720 scoped_ptr<CanonicalCookie> cc(
1760 CanonicalCookie::Create(url, cookie_line, creation_time, options)); 1721 CanonicalCookie::Create(url, cookie_line, creation_time, options));
1761 1722
1762 if (!cc.get()) { 1723 if (!cc.get()) {
1763 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie"; 1724 VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
1764 return false; 1725 return false;
1765 } 1726 }
1766 return SetCanonicalCookie(std::move(cc), options); 1727 return SetCanonicalCookie(std::move(cc), options);
1767 } 1728 }
1768 1729
1769 bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc, 1730 bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc,
1770 const CookieOptions& options) { 1731 const CookieOptions& options) {
1732 DCHECK(thread_checker_.CalledOnValidThread());
1733
1771 Time creation_time = cc->CreationDate(); 1734 Time creation_time = cc->CreationDate();
1772 const std::string key(GetKey(cc->Domain())); 1735 const std::string key(GetKey(cc->Domain()));
1773 bool already_expired = cc->IsExpired(creation_time); 1736 bool already_expired = cc->IsExpired(creation_time);
1774 1737
1775 if (DeleteAnyEquivalentCookie(key, *cc, options.exclude_httponly(), 1738 if (DeleteAnyEquivalentCookie(key, *cc, options.exclude_httponly(),
1776 already_expired, 1739 already_expired,
1777 options.enforce_strict_secure())) { 1740 options.enforce_strict_secure())) {
1778 std::string error; 1741 std::string error;
1779 if (options.enforce_strict_secure()) { 1742 if (options.enforce_strict_secure()) {
1780 error = 1743 error =
(...skipping 28 matching lines...) Expand all
1809 // querying a cookie. Since setting a cookie can put us over our limits, 1772 // 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 1773 // 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, 1774 // 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(). 1775 // and we will purge the expired cookies in GetCookies().
1813 GarbageCollect(creation_time, key, options.enforce_strict_secure()); 1776 GarbageCollect(creation_time, key, options.enforce_strict_secure());
1814 1777
1815 return true; 1778 return true;
1816 } 1779 }
1817 1780
1818 bool CookieMonster::SetCanonicalCookies(const CookieList& list) { 1781 bool CookieMonster::SetCanonicalCookies(const CookieList& list) {
1819 base::AutoLock autolock(lock_); 1782 DCHECK(thread_checker_.CalledOnValidThread());
1820 1783
1821 CookieOptions options; 1784 CookieOptions options;
1822 options.set_include_httponly(); 1785 options.set_include_httponly();
1823 1786
1824 for (const auto& cookie : list) { 1787 for (const auto& cookie : list) {
1825 if (!SetCanonicalCookie(make_scoped_ptr(new CanonicalCookie(cookie)), 1788 if (!SetCanonicalCookie(make_scoped_ptr(new CanonicalCookie(cookie)),
1826 options)) { 1789 options)) {
1827 return false; 1790 return false;
1828 } 1791 }
1829 } 1792 }
1830 1793
1831 return true; 1794 return true;
1832 } 1795 }
1833 1796
1834 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc, 1797 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie* cc,
1835 const Time& current) { 1798 const Time& current) {
1836 lock_.AssertAcquired(); 1799 DCHECK(thread_checker_.CalledOnValidThread());
1837 1800
1838 // Based off the Mozilla code. When a cookie has been accessed recently, 1801 // 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 1802 // 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 1803 // 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. 1804 // backend will hit its batch thresholds and be forced to update.
1842 if ((current - cc->LastAccessDate()) < last_access_threshold_) 1805 if ((current - cc->LastAccessDate()) < last_access_threshold_)
1843 return; 1806 return;
1844 1807
1845 cc->SetLastAccessDate(current); 1808 cc->SetLastAccessDate(current);
1846 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get()) 1809 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get())
1847 store_->UpdateCookieAccessTime(*cc); 1810 store_->UpdateCookieAccessTime(*cc);
1848 } 1811 }
1849 1812
1850 // InternalDeleteCookies must not invalidate iterators other than the one being 1813 // InternalDeleteCookies must not invalidate iterators other than the one being
1851 // deleted. 1814 // deleted.
1852 void CookieMonster::InternalDeleteCookie(CookieMap::iterator it, 1815 void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
1853 bool sync_to_store, 1816 bool sync_to_store,
1854 DeletionCause deletion_cause) { 1817 DeletionCause deletion_cause) {
1855 lock_.AssertAcquired(); 1818 DCHECK(thread_checker_.CalledOnValidThread());
1856 1819
1857 // Ideally, this would be asserted up where we define ChangeCauseMapping, 1820 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1858 // but DeletionCause's visibility (or lack thereof) forces us to make 1821 // but DeletionCause's visibility (or lack thereof) forces us to make
1859 // this check here. 1822 // this check here.
1860 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1, 1823 static_assert(arraysize(ChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
1861 "ChangeCauseMapping size should match DeletionCause size"); 1824 "ChangeCauseMapping size should match DeletionCause size");
1862 1825
1863 // See InitializeHistograms() for details. 1826 // See InitializeHistograms() for details.
1864 if (deletion_cause != DELETE_COOKIE_DONT_RECORD) 1827 if (deletion_cause != DELETE_COOKIE_DONT_RECORD)
1865 histogram_cookie_deletion_cause_->Add(deletion_cause); 1828 histogram_cookie_deletion_cause_->Add(deletion_cause);
1866 1829
1867 CanonicalCookie* cc = it->second; 1830 CanonicalCookie* cc = it->second;
1868 VLOG(kVlogSetCookies) << "InternalDeleteCookie()" 1831 VLOG(kVlogSetCookies) << "InternalDeleteCookie()"
1869 << ", cause:" << deletion_cause 1832 << ", cause:" << deletion_cause
1870 << ", cc: " << cc->DebugString(); 1833 << ", cc: " << cc->DebugString();
1871 1834
1872 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() && 1835 if ((cc->IsPersistent() || persist_session_cookies_) && store_.get() &&
1873 sync_to_store) 1836 sync_to_store)
1874 store_->DeleteCookie(*cc); 1837 store_->DeleteCookie(*cc);
1875 if (delegate_.get()) { 1838 if (delegate_.get()) {
1876 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause]; 1839 ChangeCausePair mapping = ChangeCauseMapping[deletion_cause];
1877 1840
1878 if (mapping.notify) 1841 if (mapping.notify)
1879 delegate_->OnCookieChanged(*cc, true, mapping.cause); 1842 delegate_->OnCookieChanged(*cc, true, mapping.cause);
1880 } 1843 }
1881 RunCallbacks(*cc, true); 1844 RunCookieChangedCallbacks(*cc, true);
1882 cookies_.erase(it); 1845 cookies_.erase(it);
1883 delete cc; 1846 delete cc;
1884 } 1847 }
1885 1848
1886 // Domain expiry behavior is unchanged by key/expiry scheme (the 1849 // 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). 1850 // meaning of the key is different, but that's not visible to this routine).
1888 size_t CookieMonster::GarbageCollect(const Time& current, 1851 size_t CookieMonster::GarbageCollect(const Time& current,
1889 const std::string& key, 1852 const std::string& key,
1890 bool enforce_strict_secure) { 1853 bool enforce_strict_secure) {
1891 lock_.AssertAcquired(); 1854 DCHECK(thread_checker_.CalledOnValidThread());
1892 1855
1893 size_t num_deleted = 0; 1856 size_t num_deleted = 0;
1894 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays)); 1857 Time safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays));
1895 1858
1896 // Collect garbage for this key, minding cookie priorities. 1859 // Collect garbage for this key, minding cookie priorities.
1897 if (cookies_.count(key) > kDomainMaxCookies) { 1860 if (cookies_.count(key) > kDomainMaxCookies) {
1898 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key; 1861 VLOG(kVlogGarbageCollection) << "GarbageCollect() key: " << key;
1899 1862
1900 CookieItVector cookie_its; 1863 CookieItVector cookie_its;
1901 1864
(...skipping 209 matching lines...) Expand 10 before | Expand all | Expand 10 after
2111 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle, 2074 current, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE, it_purge_middle,
2112 it_purge_end); 2075 it_purge_end);
2113 it_purge_begin = it_purge_end; 2076 it_purge_begin = it_purge_end;
2114 } 2077 }
2115 return num_deleted; 2078 return num_deleted;
2116 } 2079 }
2117 2080
2118 size_t CookieMonster::GarbageCollectExpired(const Time& current, 2081 size_t CookieMonster::GarbageCollectExpired(const Time& current,
2119 const CookieMapItPair& itpair, 2082 const CookieMapItPair& itpair,
2120 CookieItVector* cookie_its) { 2083 CookieItVector* cookie_its) {
2121 lock_.AssertAcquired(); 2084 DCHECK(thread_checker_.CalledOnValidThread());
2122 2085
2123 int num_deleted = 0; 2086 int num_deleted = 0;
2124 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) { 2087 for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
2125 CookieMap::iterator curit = it; 2088 CookieMap::iterator curit = it;
2126 ++it; 2089 ++it;
2127 2090
2128 if (curit->second->IsExpired(current)) { 2091 if (curit->second->IsExpired(current)) {
2129 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED); 2092 InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
2130 ++num_deleted; 2093 ++num_deleted;
2131 } else if (cookie_its) { 2094 } else if (cookie_its) {
2132 cookie_its->push_back(curit); 2095 cookie_its->push_back(curit);
2133 } 2096 }
2134 } 2097 }
2135 2098
2136 return num_deleted; 2099 return num_deleted;
2137 } 2100 }
2138 2101
2139 size_t CookieMonster::GarbageCollectNonSecure( 2102 size_t CookieMonster::GarbageCollectNonSecure(
2140 const CookieItVector& valid_cookies, 2103 const CookieItVector& valid_cookies,
2141 CookieItVector* cookie_its) { 2104 CookieItVector* cookie_its) {
2142 lock_.AssertAcquired(); 2105 DCHECK(thread_checker_.CalledOnValidThread());
2143 2106
2144 size_t num_deleted = 0; 2107 size_t num_deleted = 0;
2145 for (const auto& curr_cookie_it : valid_cookies) { 2108 for (const auto& curr_cookie_it : valid_cookies) {
2146 if (!curr_cookie_it->second->IsSecure()) { 2109 if (!curr_cookie_it->second->IsSecure()) {
2147 InternalDeleteCookie(curr_cookie_it, true, DELETE_COOKIE_NON_SECURE); 2110 InternalDeleteCookie(curr_cookie_it, true, DELETE_COOKIE_NON_SECURE);
2148 ++num_deleted; 2111 ++num_deleted;
2149 } else if (cookie_its) { 2112 } else if (cookie_its) {
2150 cookie_its->push_back(curr_cookie_it); 2113 cookie_its->push_back(curr_cookie_it);
2151 } 2114 }
2152 } 2115 }
2153 2116
2154 return num_deleted; 2117 return num_deleted;
2155 } 2118 }
2156 2119
2157 size_t CookieMonster::GarbageCollectDeleteRange( 2120 size_t CookieMonster::GarbageCollectDeleteRange(
2158 const Time& current, 2121 const Time& current,
2159 DeletionCause cause, 2122 DeletionCause cause,
2160 CookieItVector::iterator it_begin, 2123 CookieItVector::iterator it_begin,
2161 CookieItVector::iterator it_end) { 2124 CookieItVector::iterator it_end) {
2125 DCHECK(thread_checker_.CalledOnValidThread());
2126
2162 for (CookieItVector::iterator it = it_begin; it != it_end; it++) { 2127 for (CookieItVector::iterator it = it_begin; it != it_end; it++) {
2163 histogram_evicted_last_access_minutes_->Add( 2128 histogram_evicted_last_access_minutes_->Add(
2164 (current - (*it)->second->LastAccessDate()).InMinutes()); 2129 (current - (*it)->second->LastAccessDate()).InMinutes());
2165 InternalDeleteCookie((*it), true, cause); 2130 InternalDeleteCookie((*it), true, cause);
2166 } 2131 }
2167 return it_end - it_begin; 2132 return it_end - it_begin;
2168 } 2133 }
2169 2134
2170 size_t CookieMonster::GarbageCollectLeastRecentlyAccessed( 2135 size_t CookieMonster::GarbageCollectLeastRecentlyAccessed(
2171 const base::Time& current, 2136 const base::Time& current,
2172 const base::Time& safe_date, 2137 const base::Time& safe_date,
2173 size_t purge_goal, 2138 size_t purge_goal,
2174 CookieItVector cookie_its) { 2139 CookieItVector cookie_its) {
2140 DCHECK(thread_checker_.CalledOnValidThread());
2141
2175 // Sorts up to *and including* |cookie_its[purge_goal]|, so 2142 // Sorts up to *and including* |cookie_its[purge_goal]|, so
2176 // |earliest_access_time| will be properly assigned even if 2143 // |earliest_access_time| will be properly assigned even if
2177 // |global_purge_it| == |cookie_its.begin() + purge_goal|. 2144 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
2178 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(), purge_goal); 2145 SortLeastRecentlyAccessed(cookie_its.begin(), cookie_its.end(), purge_goal);
2179 // Find boundary to cookies older than safe_date. 2146 // Find boundary to cookies older than safe_date.
2180 CookieItVector::iterator global_purge_it = LowerBoundAccessDate( 2147 CookieItVector::iterator global_purge_it = LowerBoundAccessDate(
2181 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date); 2148 cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
2182 // Only delete the old cookies, and if strict secure is enabled, delete 2149 // Only delete the old cookies, and if strict secure is enabled, delete
2183 // non-secure ones first. 2150 // non-secure ones first.
2184 size_t num_deleted = 2151 size_t num_deleted =
(...skipping 21 matching lines...) Expand all
2206 // Arguably the right thing to do here is to make the key 2173 // 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 2174 // algorithm dependent on the scheme, and make sure that the scheme is
2208 // available everywhere the key must be obtained (specfically at backing 2175 // available everywhere the key must be obtained (specfically at backing
2209 // store load time). This would require either changing the backing store 2176 // 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 2177 // 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 2178 // separating out file cookies into their own CookieMonster instance and
2212 // thus restricting each scheme to a single cookie monster (which might 2179 // 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 2180 // be worth it, but is still too much trouble to solve what is currently a
2214 // non-problem). 2181 // non-problem).
2215 std::string CookieMonster::GetKey(const std::string& domain) const { 2182 std::string CookieMonster::GetKey(const std::string& domain) const {
2183 DCHECK(thread_checker_.CalledOnValidThread());
2184
2216 std::string effective_domain( 2185 std::string effective_domain(
2217 registry_controlled_domains::GetDomainAndRegistry( 2186 registry_controlled_domains::GetDomainAndRegistry(
2218 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)); 2187 domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
2219 if (effective_domain.empty()) 2188 if (effective_domain.empty())
2220 effective_domain = domain; 2189 effective_domain = domain;
2221 2190
2222 if (!effective_domain.empty() && effective_domain[0] == '.') 2191 if (!effective_domain.empty() && effective_domain[0] == '.')
2223 return effective_domain.substr(1); 2192 return effective_domain.substr(1);
2224 return effective_domain; 2193 return effective_domain;
2225 } 2194 }
2226 2195
2227 bool CookieMonster::HasCookieableScheme(const GURL& url) { 2196 bool CookieMonster::HasCookieableScheme(const GURL& url) {
2228 lock_.AssertAcquired(); 2197 DCHECK(thread_checker_.CalledOnValidThread());
2229 2198
2230 // Make sure the request is on a cookie-able url scheme. 2199 // Make sure the request is on a cookie-able url scheme.
2231 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) { 2200 for (size_t i = 0; i < cookieable_schemes_.size(); ++i) {
2232 // We matched a scheme. 2201 // We matched a scheme.
2233 if (url.SchemeIs(cookieable_schemes_[i].c_str())) { 2202 if (url.SchemeIs(cookieable_schemes_[i].c_str())) {
2234 // We've matched a supported scheme. 2203 // We've matched a supported scheme.
2235 return true; 2204 return true;
2236 } 2205 }
2237 } 2206 }
2238 2207
2239 // The scheme didn't match any in our whitelist. 2208 // The scheme didn't match any in our whitelist.
2240 VLOG(kVlogPerCookieMonster) 2209 VLOG(kVlogPerCookieMonster)
2241 << "WARNING: Unsupported cookie scheme: " << url.scheme(); 2210 << "WARNING: Unsupported cookie scheme: " << url.scheme();
2242 return false; 2211 return false;
2243 } 2212 }
2244 2213
2245 // Test to see if stats should be recorded, and record them if so. 2214 // 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 2215 // 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, 2216 // 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 2217 // and when the web is being surfed, we'll take samples about every
2249 // kRecordStatisticsIntervalSeconds. 2218 // kRecordStatisticsIntervalSeconds.
2250 // last_statistic_record_time_ is initialized to Now() rather than null 2219 // last_statistic_record_time_ is initialized to Now() rather than null
2251 // in the constructor so that we won't take statistics right after 2220 // 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. 2221 // startup, to avoid bias from browsers that are started but not used.
2253 void CookieMonster::RecordPeriodicStats(const base::Time& current_time) { 2222 void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
2223 DCHECK(thread_checker_.CalledOnValidThread());
2224
2254 const base::TimeDelta kRecordStatisticsIntervalTime( 2225 const base::TimeDelta kRecordStatisticsIntervalTime(
2255 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds)); 2226 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds));
2256 2227
2257 // If we've taken statistics recently, return. 2228 // If we've taken statistics recently, return.
2258 if (current_time - last_statistic_record_time_ <= 2229 if (current_time - last_statistic_record_time_ <=
2259 kRecordStatisticsIntervalTime) { 2230 kRecordStatisticsIntervalTime) {
2260 return; 2231 return;
2261 } 2232 }
2262 2233
2263 // See InitializeHistograms() for details. 2234 // See InitializeHistograms() for details.
(...skipping 20 matching lines...) Expand all
2284 // Note that these variables refer to the same underlying histogram, 2255 // Note that these variables refer to the same underlying histogram,
2285 // so we still race (but safely) with other CookieMonster instances 2256 // so we still race (but safely) with other CookieMonster instances
2286 // for accumulation. 2257 // for accumulation.
2287 // 2258 //
2288 // To do this we've expanded out the individual histogram macros calls, 2259 // To do this we've expanded out the individual histogram macros calls,
2289 // with declarations of the variables in the class decl, initialization here 2260 // with declarations of the variables in the class decl, initialization here
2290 // (done from the class constructor) and direct calls to the accumulation 2261 // (done from the class constructor) and direct calls to the accumulation
2291 // methods where needed. The specific histogram macro calls on which the 2262 // methods where needed. The specific histogram macro calls on which the
2292 // initialization is based are included in comments below. 2263 // initialization is based are included in comments below.
2293 void CookieMonster::InitializeHistograms() { 2264 void CookieMonster::InitializeHistograms() {
2265 DCHECK(thread_checker_.CalledOnValidThread());
2266
2294 // From UMA_HISTOGRAM_CUSTOM_COUNTS 2267 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2295 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet( 2268 histogram_expiration_duration_minutes_ = base::Histogram::FactoryGet(
2296 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50, 2269 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears, 50,
2297 base::Histogram::kUmaTargetedHistogramFlag); 2270 base::Histogram::kUmaTargetedHistogramFlag);
2298 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet( 2271 histogram_evicted_last_access_minutes_ = base::Histogram::FactoryGet(
2299 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50, 2272 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears, 50,
2300 base::Histogram::kUmaTargetedHistogramFlag); 2273 base::Histogram::kUmaTargetedHistogramFlag);
2301 histogram_count_ = base::Histogram::FactoryGet( 2274 histogram_count_ = base::Histogram::FactoryGet(
2302 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag); 2275 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag);
2303 2276
(...skipping 23 matching lines...) Expand all
2327 // The system resolution is not high enough, so we can have multiple 2300 // 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 2301 // 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. 2302 // increment by one Time unit. Let's hope computers don't get too fast.
2330 Time CookieMonster::CurrentTime() { 2303 Time CookieMonster::CurrentTime() {
2331 return std::max(Time::Now(), Time::FromInternalValue( 2304 return std::max(Time::Now(), Time::FromInternalValue(
2332 last_time_seen_.ToInternalValue() + 1)); 2305 last_time_seen_.ToInternalValue() + 1));
2333 } 2306 }
2334 2307
2335 void CookieMonster::DoCookieTask( 2308 void CookieMonster::DoCookieTask(
2336 const scoped_refptr<CookieMonsterTask>& task_item) { 2309 const scoped_refptr<CookieMonsterTask>& task_item) {
2337 { 2310 DCHECK(thread_checker_.CalledOnValidThread());
2338 base::AutoLock autolock(lock_); 2311
2339 MarkCookieStoreAsInitialized(); 2312 MarkCookieStoreAsInitialized();
2340 FetchAllCookiesIfNecessary(); 2313 FetchAllCookiesIfNecessary();
2341 if (!finished_fetching_all_cookies_ && store_.get()) { 2314
2342 tasks_pending_.push(task_item); 2315 if (!finished_fetching_all_cookies_ && store_.get()) {
2343 return; 2316 tasks_pending_.push(task_item);
2344 } 2317 return;
2345 } 2318 }
2346 2319
2347 task_item->Run(); 2320 task_item->Run();
2348 } 2321 }
2349 2322
2350 void CookieMonster::DoCookieTaskForURL( 2323 void CookieMonster::DoCookieTaskForURL(
2351 const scoped_refptr<CookieMonsterTask>& task_item, 2324 const scoped_refptr<CookieMonsterTask>& task_item,
2352 const GURL& url) { 2325 const GURL& url) {
2353 { 2326 DCHECK(thread_checker_.CalledOnValidThread());
2354 base::AutoLock autolock(lock_); 2327
2355 MarkCookieStoreAsInitialized(); 2328 MarkCookieStoreAsInitialized();
2356 if (ShouldFetchAllCookiesWhenFetchingAnyCookie()) 2329 if (ShouldFetchAllCookiesWhenFetchingAnyCookie())
2357 FetchAllCookiesIfNecessary(); 2330 FetchAllCookiesIfNecessary();
2358 // If cookies for the requested domain key (eTLD+1) have been loaded from DB 2331
2359 // then run the task, otherwise load from DB. 2332 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
2360 if (!finished_fetching_all_cookies_ && store_.get()) { 2333 // then run the task, otherwise load from DB.
2361 // Checks if the domain key has been loaded. 2334 if (!finished_fetching_all_cookies_ && store_.get()) {
2362 std::string key( 2335 // Checks if the domain key has been loaded.
2363 cookie_util::GetEffectiveDomain(url.scheme(), url.host())); 2336 std::string key(cookie_util::GetEffectiveDomain(url.scheme(), url.host()));
2364 if (keys_loaded_.find(key) == keys_loaded_.end()) { 2337 if (keys_loaded_.find(key) == keys_loaded_.end()) {
2365 std::map<std::string, 2338 std::map<std::string,
2366 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it = 2339 std::deque<scoped_refptr<CookieMonsterTask>>>::iterator it =
2367 tasks_pending_for_key_.find(key); 2340 tasks_pending_for_key_.find(key);
2368 if (it == tasks_pending_for_key_.end()) { 2341 if (it == tasks_pending_for_key_.end()) {
2369 store_->LoadCookiesForKey( 2342 store_->LoadCookiesForKey(
2370 key, base::Bind(&CookieMonster::OnKeyLoaded, this, key)); 2343 key, base::Bind(&CookieMonster::OnKeyLoaded,
2371 it = tasks_pending_for_key_ 2344 weak_ptr_factory_.GetWeakPtr(), key));
2372 .insert(std::make_pair( 2345 it = tasks_pending_for_key_
2373 key, std::deque<scoped_refptr<CookieMonsterTask>>())) 2346 .insert(std::make_pair(
2374 .first; 2347 key, std::deque<scoped_refptr<CookieMonsterTask>>()))
2375 } 2348 .first;
2376 it->second.push_back(task_item);
2377 return;
2378 } 2349 }
2350 it->second.push_back(task_item);
2351 return;
2379 } 2352 }
2380 } 2353 }
2354
2381 task_item->Run(); 2355 task_item->Run();
2382 } 2356 }
2383 2357
2384 void CookieMonster::ComputeCookieDiff(CookieList* old_cookies, 2358 void CookieMonster::ComputeCookieDiff(CookieList* old_cookies,
2385 CookieList* new_cookies, 2359 CookieList* new_cookies,
2386 CookieList* cookies_to_add, 2360 CookieList* cookies_to_add,
2387 CookieList* cookies_to_delete) { 2361 CookieList* cookies_to_delete) {
2362 DCHECK(thread_checker_.CalledOnValidThread());
2363
2388 DCHECK(old_cookies); 2364 DCHECK(old_cookies);
2389 DCHECK(new_cookies); 2365 DCHECK(new_cookies);
2390 DCHECK(cookies_to_add); 2366 DCHECK(cookies_to_add);
2391 DCHECK(cookies_to_delete); 2367 DCHECK(cookies_to_delete);
2392 DCHECK(cookies_to_add->empty()); 2368 DCHECK(cookies_to_add->empty());
2393 DCHECK(cookies_to_delete->empty()); 2369 DCHECK(cookies_to_delete->empty());
2394 2370
2395 // Sort both lists. 2371 // Sort both lists.
2396 // A set ordered by FullDiffCookieSorter is also ordered by 2372 // A set ordered by FullDiffCookieSorter is also ordered by
2397 // PartialDiffCookieSorter. 2373 // PartialDiffCookieSorter.
2398 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter); 2374 std::sort(old_cookies->begin(), old_cookies->end(), FullDiffCookieSorter);
2399 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter); 2375 std::sort(new_cookies->begin(), new_cookies->end(), FullDiffCookieSorter);
2400 2376
2401 // Select any old cookie for deletion if no new cookie has the same name, 2377 // Select any old cookie for deletion if no new cookie has the same name,
2402 // domain, and path. 2378 // domain, and path.
2403 std::set_difference( 2379 std::set_difference(
2404 old_cookies->begin(), old_cookies->end(), new_cookies->begin(), 2380 old_cookies->begin(), old_cookies->end(), new_cookies->begin(),
2405 new_cookies->end(), 2381 new_cookies->end(),
2406 std::inserter(*cookies_to_delete, cookies_to_delete->begin()), 2382 std::inserter(*cookies_to_delete, cookies_to_delete->begin()),
2407 PartialDiffCookieSorter); 2383 PartialDiffCookieSorter);
2408 2384
2409 // Select any new cookie for addition (or update) if no old cookie is exactly 2385 // Select any new cookie for addition (or update) if no old cookie is exactly
2410 // equivalent. 2386 // equivalent.
2411 std::set_difference(new_cookies->begin(), new_cookies->end(), 2387 std::set_difference(new_cookies->begin(), new_cookies->end(),
2412 old_cookies->begin(), old_cookies->end(), 2388 old_cookies->begin(), old_cookies->end(),
2413 std::inserter(*cookies_to_add, cookies_to_add->begin()), 2389 std::inserter(*cookies_to_add, cookies_to_add->begin()),
2414 FullDiffCookieSorter); 2390 FullDiffCookieSorter);
2415 } 2391 }
2416 2392
2417 void CookieMonster::RunCallbacks(const CanonicalCookie& cookie, bool removed) { 2393 void CookieMonster::RunCallback(const base::Closure& callback) {
2418 lock_.AssertAcquired(); 2394 DCHECK(thread_checker_.CalledOnValidThread());
2395 callback.Run();
2396 }
2397
2398 void CookieMonster::RunCookieChangedCallbacks(const CanonicalCookie& cookie,
2399 bool removed) {
2400 DCHECK(thread_checker_.CalledOnValidThread());
2401
2419 CookieOptions opts; 2402 CookieOptions opts;
2420 opts.set_include_httponly(); 2403 opts.set_include_httponly();
2421 opts.set_include_same_site(); 2404 opts.set_include_same_site();
2422 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they 2405 // 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 2406 // 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 2407 // the appropriate thread's message loop and return.
2425 // method not run user-supplied callbacks directly, since the CookieMonster 2408 // 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(); 2409 for (CookieChangedHookMap::iterator it = hook_map_.begin();
2428 it != hook_map_.end(); ++it) { 2410 it != hook_map_.end(); ++it) {
2429 std::pair<GURL, std::string> key = it->first; 2411 std::pair<GURL, std::string> key = it->first;
2430 if (cookie.IncludeForRequestURL(key.first, opts) && 2412 if (cookie.IncludeForRequestURL(key.first, opts) &&
2431 cookie.Name() == key.second) { 2413 cookie.Name() == key.second) {
2432 it->second->Notify(cookie, removed); 2414 it->second->Notify(cookie, removed);
2433 } 2415 }
2434 } 2416 }
2435 } 2417 }
2436 2418
2437 } // namespace net 2419 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698