1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Portions of this code based on Mozilla:
6 // (netwerk/cookie/src/nsCookieService.cpp)
7 /* ***** BEGIN LICENSE BLOCK *****
8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
10 * The contents of this file are subject to the Mozilla Public License Version
11 * 1.1 (the "License"); you may not use this file except in compliance with
12 * the License. You may obtain a copy of the License at
13 * http://www.mozilla.org/MPL/
15 * Software distributed under the License is distributed on an "AS IS" basis,
16 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
17 * for the specific language governing rights and limitations under the
20 * The Original Code is mozilla.org code.
22 * The Initial Developer of the Original Code is
23 * Netscape Communications Corporation.
24 * Portions created by the Initial Developer are Copyright (C) 2003
25 * the Initial Developer. All Rights Reserved.
28 * Daniel Witte (dwitte@stanford.edu)
29 * Michiel van Leeuwen (mvl@exedo.nl)
31 * Alternatively, the contents of this file may be used under the terms of
32 * either the GNU General Public License Version 2 or later (the "GPL"), or
33 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
34 * in which case the provisions of the GPL or the LGPL are applicable instead
35 * of those above. If you wish to allow use of your version of this file only
36 * under the terms of either the GPL or the LGPL, and not to allow others to
37 * use your version of this file under the terms of the MPL, indicate your
38 * decision by deleting the provisions above and replace them with the notice
39 * and other provisions required by the GPL or the LGPL. If you do not delete
40 * the provisions above, a recipient may use your version of this file under
41 * the terms of any one of the MPL, the GPL or the LGPL.
43 * ***** END LICENSE BLOCK ***** */
45 #include "net/cookies/cookie_monster.h"
51 #include "base/basictypes.h"
52 #include "base/bind.h"
53 #include "base/callback.h"
54 #include "base/logging.h"
55 #include "base/memory/scoped_ptr.h"
56 #include "base/memory/scoped_vector.h"
57 #include "base/message_loop/message_loop.h"
58 #include "base/message_loop/message_loop_proxy.h"
59 #include "base/metrics/histogram.h"
60 #include "base/profiler/scoped_tracker.h"
61 #include "base/strings/string_util.h"
62 #include "base/strings/stringprintf.h"
63 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
64 #include "net/cookies/canonical_cookie.h"
65 #include "net/cookies/cookie_util.h"
66 #include "net/cookies/parsed_cookie.h"
69 using base::TimeDelta
;
70 using base::TimeTicks
;
72 // In steady state, most cookie requests can be satisfied by the in memory
73 // cookie monster store. However, if a request comes in during the initial
74 // cookie load, it must be delayed until that load completes. That is done by
75 // queueing it on CookieMonster::tasks_pending_ and running it when notification
76 // of cookie load completion is received via CookieMonster::OnLoaded. This
77 // callback is passed to the persistent store from CookieMonster::InitStore(),
78 // which is called on the first operation invoked on the CookieMonster.
80 // On the browser critical paths (e.g. for loading initial web pages in a
81 // session restore) it may take too long to wait for the full load. If a cookie
82 // request is for a specific URL, DoCookieTaskForURL is called, which triggers a
83 // priority load if the key is not loaded yet by calling PersistentCookieStore
84 // :: LoadCookiesForKey. The request is queued in
85 // CookieMonster::tasks_pending_for_key_ and executed upon receiving
86 // notification of key load completion via CookieMonster::OnKeyLoaded(). If
87 // multiple requests for the same eTLD+1 are received before key load
88 // completion, only the first request calls
89 // PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
90 // in CookieMonster::tasks_pending_for_key_ and executed upon receiving
91 // notification of key load completion triggered by the first request for the
94 static const int kMinutesInTenYears
= 10 * 365 * 24 * 60;
98 // See comments at declaration of these variables in cookie_monster.h
100 const size_t CookieMonster::kDomainMaxCookies
= 180;
101 const size_t CookieMonster::kDomainPurgeCookies
= 30;
102 const size_t CookieMonster::kMaxCookies
= 3300;
103 const size_t CookieMonster::kPurgeCookies
= 300;
105 const size_t CookieMonster::kDomainCookiesQuotaLow
= 30;
106 const size_t CookieMonster::kDomainCookiesQuotaMedium
= 50;
107 const size_t CookieMonster::kDomainCookiesQuotaHigh
=
108 kDomainMaxCookies
- kDomainPurgeCookies
- kDomainCookiesQuotaLow
-
109 kDomainCookiesQuotaMedium
;
111 const int CookieMonster::kSafeFromGlobalPurgeDays
= 30;
115 bool ContainsControlCharacter(const std::string
& s
) {
116 for (std::string::const_iterator i
= s
.begin(); i
!= s
.end(); ++i
) {
117 if ((*i
>= 0) && (*i
<= 31))
124 typedef std::vector
<CanonicalCookie
*> CanonicalCookieVector
;
126 // Default minimum delay after updating a cookie's LastAccessDate before we
127 // will update it again.
128 const int kDefaultAccessUpdateThresholdSeconds
= 60;
130 // Comparator to sort cookies from highest creation date to lowest
132 struct OrderByCreationTimeDesc
{
133 bool operator()(const CookieMonster::CookieMap::iterator
& a
,
134 const CookieMonster::CookieMap::iterator
& b
) const {
135 return a
->second
->CreationDate() > b
->second
->CreationDate();
139 // Constants for use in VLOG
140 const int kVlogPerCookieMonster
= 1;
141 const int kVlogPeriodic
= 3;
142 const int kVlogGarbageCollection
= 5;
143 const int kVlogSetCookies
= 7;
144 const int kVlogGetCookies
= 9;
146 // Mozilla sorts on the path length (longest first), and then it
147 // sorts by creation time (oldest first).
148 // The RFC says the sort order for the domain attribute is undefined.
149 bool CookieSorter(CanonicalCookie
* cc1
, CanonicalCookie
* cc2
) {
150 if (cc1
->Path().length() == cc2
->Path().length())
151 return cc1
->CreationDate() < cc2
->CreationDate();
152 return cc1
->Path().length() > cc2
->Path().length();
155 bool LRACookieSorter(const CookieMonster::CookieMap::iterator
& it1
,
156 const CookieMonster::CookieMap::iterator
& it2
) {
157 // Cookies accessed less recently should be deleted first.
158 if (it1
->second
->LastAccessDate() != it2
->second
->LastAccessDate())
159 return it1
->second
->LastAccessDate() < it2
->second
->LastAccessDate();
161 // In rare cases we might have two cookies with identical last access times.
162 // To preserve the stability of the sort, in these cases prefer to delete
163 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
164 return it1
->second
->CreationDate() < it2
->second
->CreationDate();
167 // Our strategy to find duplicates is:
168 // (1) Build a map from (cookiename, cookiepath) to
169 // {list of cookies with this signature, sorted by creation time}.
170 // (2) For each list with more than 1 entry, keep the cookie having the
171 // most recent creation time, and delete the others.
173 // Two cookies are considered equivalent if they have the same domain,
175 struct CookieSignature
{
177 CookieSignature(const std::string
& name
,
178 const std::string
& domain
,
179 const std::string
& path
)
180 : name(name
), domain(domain
), path(path
) {}
182 // To be a key for a map this class needs to be assignable, copyable,
183 // and have an operator<. The default assignment operator
184 // and copy constructor are exactly what we want.
186 bool operator<(const CookieSignature
& cs
) const {
187 // Name compare dominates, then domain, then path.
188 int diff
= name
.compare(cs
.name
);
192 diff
= domain
.compare(cs
.domain
);
196 return path
.compare(cs
.path
) < 0;
204 // For a CookieItVector iterator range [|it_begin|, |it_end|),
205 // sorts the first |num_sort| + 1 elements by LastAccessDate().
206 // The + 1 element exists so for any interval of length <= |num_sort| starting
207 // from |cookies_its_begin|, a LastAccessDate() bound can be found.
208 void SortLeastRecentlyAccessed(CookieMonster::CookieItVector::iterator it_begin
,
209 CookieMonster::CookieItVector::iterator it_end
,
211 DCHECK_LT(static_cast<int>(num_sort
), it_end
- it_begin
);
212 std::partial_sort(it_begin
, it_begin
+ num_sort
+ 1, it_end
, LRACookieSorter
);
215 // Predicate to support PartitionCookieByPriority().
216 struct CookiePriorityEqualsTo
217 : std::unary_function
<const CookieMonster::CookieMap::iterator
, bool> {
218 explicit CookiePriorityEqualsTo(CookiePriority priority
)
219 : priority_(priority
) {}
221 bool operator()(const CookieMonster::CookieMap::iterator it
) const {
222 return it
->second
->Priority() == priority_
;
225 const CookiePriority priority_
;
228 // For a CookieItVector iterator range [|it_begin|, |it_end|),
229 // moves all cookies with a given |priority| to the beginning of the list.
230 // Returns: An iterator in [it_begin, it_end) to the first element with
231 // priority != |priority|, or |it_end| if all have priority == |priority|.
232 CookieMonster::CookieItVector::iterator
PartitionCookieByPriority(
233 CookieMonster::CookieItVector::iterator it_begin
,
234 CookieMonster::CookieItVector::iterator it_end
,
235 CookiePriority priority
) {
236 return std::partition(it_begin
, it_end
, CookiePriorityEqualsTo(priority
));
239 bool LowerBoundAccessDateComparator(const CookieMonster::CookieMap::iterator it
,
240 const Time
& access_date
) {
241 return it
->second
->LastAccessDate() < access_date
;
244 // For a CookieItVector iterator range [|it_begin|, |it_end|)
245 // from a CookieItVector sorted by LastAccessDate(), returns the
246 // first iterator with access date >= |access_date|, or cookie_its_end if this
248 CookieMonster::CookieItVector::iterator
LowerBoundAccessDate(
249 const CookieMonster::CookieItVector::iterator its_begin
,
250 const CookieMonster::CookieItVector::iterator its_end
,
251 const Time
& access_date
) {
252 return std::lower_bound(its_begin
, its_end
, access_date
,
253 LowerBoundAccessDateComparator
);
256 // Mapping between DeletionCause and CookieMonsterDelegate::ChangeCause; the
257 // mapping also provides a boolean that specifies whether or not an
258 // OnCookieChanged notification ought to be generated.
259 typedef struct ChangeCausePair_struct
{
260 CookieMonsterDelegate::ChangeCause cause
;
263 ChangeCausePair ChangeCauseMapping
[] = {
264 // DELETE_COOKIE_EXPLICIT
265 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, true},
266 // DELETE_COOKIE_OVERWRITE
267 {CookieMonsterDelegate::CHANGE_COOKIE_OVERWRITE
, true},
268 // DELETE_COOKIE_EXPIRED
269 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED
, true},
270 // DELETE_COOKIE_EVICTED
271 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
272 // DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
273 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, false},
274 // DELETE_COOKIE_DONT_RECORD
275 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, false},
276 // DELETE_COOKIE_EVICTED_DOMAIN
277 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
278 // DELETE_COOKIE_EVICTED_GLOBAL
279 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
280 // DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
281 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
282 // DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
283 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
284 // DELETE_COOKIE_EXPIRED_OVERWRITE
285 {CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED_OVERWRITE
, true},
286 // DELETE_COOKIE_CONTROL_CHAR
287 {CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
288 // DELETE_COOKIE_LAST_ENTRY
289 {CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, false}};
291 std::string
BuildCookieLine(const CanonicalCookieVector
& cookies
) {
292 std::string cookie_line
;
293 for (CanonicalCookieVector::const_iterator it
= cookies
.begin();
294 it
!= cookies
.end(); ++it
) {
295 if (it
!= cookies
.begin())
297 // In Mozilla if you set a cookie like AAAA, it will have an empty token
298 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
299 // so we need to avoid sending =AAAA for a blank token value.
300 if (!(*it
)->Name().empty())
301 cookie_line
+= (*it
)->Name() + "=";
302 cookie_line
+= (*it
)->Value();
307 void RunAsync(scoped_refptr
<base::TaskRunner
> proxy
,
308 const CookieStore::CookieChangedCallback
& callback
,
309 const CanonicalCookie
& cookie
,
311 proxy
->PostTask(FROM_HERE
, base::Bind(callback
, cookie
, removed
));
316 CookieMonster::CookieMonster(PersistentCookieStore
* store
,
317 CookieMonsterDelegate
* delegate
)
318 : initialized_(false),
319 loaded_(store
== NULL
),
321 last_access_threshold_(
322 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds
)),
324 last_statistic_record_time_(Time::Now()),
325 keep_expired_cookies_(false),
326 persist_session_cookies_(false) {
327 InitializeHistograms();
328 SetDefaultCookieableSchemes();
331 CookieMonster::CookieMonster(PersistentCookieStore
* store
,
332 CookieMonsterDelegate
* delegate
,
333 int last_access_threshold_milliseconds
)
334 : initialized_(false),
335 loaded_(store
== NULL
),
337 last_access_threshold_(base::TimeDelta::FromMilliseconds(
338 last_access_threshold_milliseconds
)),
340 last_statistic_record_time_(base::Time::Now()),
341 keep_expired_cookies_(false),
342 persist_session_cookies_(false) {
343 InitializeHistograms();
344 SetDefaultCookieableSchemes();
347 // Task classes for queueing the coming request.
349 class CookieMonster::CookieMonsterTask
350 : public base::RefCountedThreadSafe
<CookieMonsterTask
> {
352 // Runs the task and invokes the client callback on the thread that
353 // originally constructed the task.
354 virtual void Run() = 0;
357 explicit CookieMonsterTask(CookieMonster
* cookie_monster
);
358 virtual ~CookieMonsterTask();
360 // Invokes the callback immediately, if the current thread is the one
361 // that originated the task, or queues the callback for execution on the
362 // appropriate thread. Maintains a reference to this CookieMonsterTask
363 // instance until the callback completes.
364 void InvokeCallback(base::Closure callback
);
366 CookieMonster
* cookie_monster() { return cookie_monster_
; }
369 friend class base::RefCountedThreadSafe
<CookieMonsterTask
>;
371 CookieMonster
* cookie_monster_
;
372 scoped_refptr
<base::MessageLoopProxy
> thread_
;
374 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask
);
377 CookieMonster::CookieMonsterTask::CookieMonsterTask(
378 CookieMonster
* cookie_monster
)
379 : cookie_monster_(cookie_monster
),
380 thread_(base::MessageLoopProxy::current()) {
383 CookieMonster::CookieMonsterTask::~CookieMonsterTask() {
386 // Unfortunately, one cannot re-bind a Callback with parameters into a closure.
387 // Therefore, the closure passed to InvokeCallback is a clumsy binding of
388 // Callback::Run on a wrapped Callback instance. Since Callback is not
389 // reference counted, we bind to an instance that is a member of the
390 // CookieMonsterTask subclass. Then, we cannot simply post the callback to a
391 // message loop because the underlying instance may be destroyed (along with the
392 // CookieMonsterTask instance) in the interim. Therefore, we post a callback
393 // bound to the CookieMonsterTask, which *is* reference counted (thus preventing
394 // destruction of the original callback), and which invokes the closure (which
395 // invokes the original callback with the returned data).
396 void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback
) {
397 if (thread_
->BelongsToCurrentThread()) {
400 thread_
->PostTask(FROM_HERE
, base::Bind(&CookieMonsterTask::InvokeCallback
,
405 // Task class for SetCookieWithDetails call.
406 class CookieMonster::SetCookieWithDetailsTask
: public CookieMonsterTask
{
408 SetCookieWithDetailsTask(CookieMonster
* cookie_monster
,
410 const std::string
& name
,
411 const std::string
& value
,
412 const std::string
& domain
,
413 const std::string
& path
,
414 const base::Time
& expiration_time
,
417 bool first_party_only
,
418 CookiePriority priority
,
419 const SetCookiesCallback
& callback
)
420 : CookieMonsterTask(cookie_monster
),
426 expiration_time_(expiration_time
),
428 http_only_(http_only
),
429 first_party_only_(first_party_only
),
431 callback_(callback
) {}
433 // CookieMonsterTask:
437 ~SetCookieWithDetailsTask() override
{}
445 base::Time expiration_time_
;
448 bool first_party_only_
;
449 CookiePriority priority_
;
450 SetCookiesCallback callback_
;
452 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask
);
455 void CookieMonster::SetCookieWithDetailsTask::Run() {
456 bool success
= this->cookie_monster()->SetCookieWithDetails(
457 url_
, name_
, value_
, domain_
, path_
, expiration_time_
, secure_
,
458 http_only_
, first_party_only_
, priority_
);
459 if (!callback_
.is_null()) {
460 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run
,
461 base::Unretained(&callback_
), success
));
465 // Task class for GetAllCookies call.
466 class CookieMonster::GetAllCookiesTask
: public CookieMonsterTask
{
468 GetAllCookiesTask(CookieMonster
* cookie_monster
,
469 const GetCookieListCallback
& callback
)
470 : CookieMonsterTask(cookie_monster
), callback_(callback
) {}
476 ~GetAllCookiesTask() override
{}
479 GetCookieListCallback callback_
;
481 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask
);
484 void CookieMonster::GetAllCookiesTask::Run() {
485 if (!callback_
.is_null()) {
486 CookieList cookies
= this->cookie_monster()->GetAllCookies();
487 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run
,
488 base::Unretained(&callback_
), cookies
));
492 // Task class for GetAllCookiesForURLWithOptions call.
493 class CookieMonster::GetAllCookiesForURLWithOptionsTask
494 : public CookieMonsterTask
{
496 GetAllCookiesForURLWithOptionsTask(CookieMonster
* cookie_monster
,
498 const CookieOptions
& options
,
499 const GetCookieListCallback
& callback
)
500 : CookieMonsterTask(cookie_monster
),
503 callback_(callback
) {}
505 // CookieMonsterTask:
509 ~GetAllCookiesForURLWithOptionsTask() override
{}
513 CookieOptions options_
;
514 GetCookieListCallback callback_
;
516 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask
);
519 void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
520 if (!callback_
.is_null()) {
522 this->cookie_monster()->GetAllCookiesForURLWithOptions(url_
, options_
);
523 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run
,
524 base::Unretained(&callback_
), cookies
));
528 template <typename Result
>
529 struct CallbackType
{
530 typedef base::Callback
<void(Result
)> Type
;
534 struct CallbackType
<void> {
535 typedef base::Closure Type
;
538 // Base task class for Delete*Task.
539 template <typename Result
>
540 class CookieMonster::DeleteTask
: public CookieMonsterTask
{
542 DeleteTask(CookieMonster
* cookie_monster
,
543 const typename CallbackType
<Result
>::Type
& callback
)
544 : CookieMonsterTask(cookie_monster
), callback_(callback
) {}
546 // CookieMonsterTask:
547 virtual void Run() override
;
550 ~DeleteTask() override
;
553 // Runs the delete task and returns a result.
554 virtual Result
RunDeleteTask() = 0;
555 base::Closure
RunDeleteTaskAndBindCallback();
556 void FlushDone(const base::Closure
& callback
);
558 typename CallbackType
<Result
>::Type callback_
;
560 DISALLOW_COPY_AND_ASSIGN(DeleteTask
);
563 template <typename Result
>
564 CookieMonster::DeleteTask
<Result
>::~DeleteTask() {
567 template <typename Result
>
569 CookieMonster::DeleteTask
<Result
>::RunDeleteTaskAndBindCallback() {
570 Result result
= RunDeleteTask();
571 if (callback_
.is_null())
572 return base::Closure();
573 return base::Bind(callback_
, result
);
577 base::Closure
CookieMonster::DeleteTask
<void>::RunDeleteTaskAndBindCallback() {
582 template <typename Result
>
583 void CookieMonster::DeleteTask
<Result
>::Run() {
584 this->cookie_monster()->FlushStore(base::Bind(
585 &DeleteTask
<Result
>::FlushDone
, this, RunDeleteTaskAndBindCallback()));
588 template <typename Result
>
589 void CookieMonster::DeleteTask
<Result
>::FlushDone(
590 const base::Closure
& callback
) {
591 if (!callback
.is_null()) {
592 this->InvokeCallback(callback
);
596 // Task class for DeleteAll call.
597 class CookieMonster::DeleteAllTask
: public DeleteTask
<int> {
599 DeleteAllTask(CookieMonster
* cookie_monster
, const DeleteCallback
& callback
)
600 : DeleteTask
<int>(cookie_monster
, callback
) {}
603 int RunDeleteTask() override
;
606 ~DeleteAllTask() override
{}
609 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask
);
612 int CookieMonster::DeleteAllTask::RunDeleteTask() {
613 return this->cookie_monster()->DeleteAll(true);
616 // Task class for DeleteAllCreatedBetween call.
617 class CookieMonster::DeleteAllCreatedBetweenTask
: public DeleteTask
<int> {
619 DeleteAllCreatedBetweenTask(CookieMonster
* cookie_monster
,
620 const Time
& delete_begin
,
621 const Time
& delete_end
,
622 const DeleteCallback
& callback
)
623 : DeleteTask
<int>(cookie_monster
, callback
),
624 delete_begin_(delete_begin
),
625 delete_end_(delete_end
) {}
628 int RunDeleteTask() override
;
631 ~DeleteAllCreatedBetweenTask() override
{}
637 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask
);
640 int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
641 return this->cookie_monster()->DeleteAllCreatedBetween(delete_begin_
,
645 // Task class for DeleteAllForHost call.
646 class CookieMonster::DeleteAllForHostTask
: public DeleteTask
<int> {
648 DeleteAllForHostTask(CookieMonster
* cookie_monster
,
650 const DeleteCallback
& callback
)
651 : DeleteTask
<int>(cookie_monster
, callback
), url_(url
) {}
654 int RunDeleteTask() override
;
657 ~DeleteAllForHostTask() override
{}
662 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask
);
665 int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
666 return this->cookie_monster()->DeleteAllForHost(url_
);
669 // Task class for DeleteAllCreatedBetweenForHost call.
670 class CookieMonster::DeleteAllCreatedBetweenForHostTask
671 : public DeleteTask
<int> {
673 DeleteAllCreatedBetweenForHostTask(CookieMonster
* cookie_monster
,
677 const DeleteCallback
& callback
)
678 : DeleteTask
<int>(cookie_monster
, callback
),
679 delete_begin_(delete_begin
),
680 delete_end_(delete_end
),
684 int RunDeleteTask() override
;
687 ~DeleteAllCreatedBetweenForHostTask() override
{}
694 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenForHostTask
);
697 int CookieMonster::DeleteAllCreatedBetweenForHostTask::RunDeleteTask() {
698 return this->cookie_monster()->DeleteAllCreatedBetweenForHost(
699 delete_begin_
, delete_end_
, url_
);
702 // Task class for DeleteCanonicalCookie call.
703 class CookieMonster::DeleteCanonicalCookieTask
: public DeleteTask
<bool> {
705 DeleteCanonicalCookieTask(CookieMonster
* cookie_monster
,
706 const CanonicalCookie
& cookie
,
707 const DeleteCookieCallback
& callback
)
708 : DeleteTask
<bool>(cookie_monster
, callback
), cookie_(cookie
) {}
711 bool RunDeleteTask() override
;
714 ~DeleteCanonicalCookieTask() override
{}
717 CanonicalCookie cookie_
;
719 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask
);
722 bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
723 return this->cookie_monster()->DeleteCanonicalCookie(cookie_
);
726 // Task class for SetCookieWithOptions call.
727 class CookieMonster::SetCookieWithOptionsTask
: public CookieMonsterTask
{
729 SetCookieWithOptionsTask(CookieMonster
* cookie_monster
,
731 const std::string
& cookie_line
,
732 const CookieOptions
& options
,
733 const SetCookiesCallback
& callback
)
734 : CookieMonsterTask(cookie_monster
),
736 cookie_line_(cookie_line
),
738 callback_(callback
) {}
740 // CookieMonsterTask:
744 ~SetCookieWithOptionsTask() override
{}
748 std::string cookie_line_
;
749 CookieOptions options_
;
750 SetCookiesCallback callback_
;
752 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask
);
755 void CookieMonster::SetCookieWithOptionsTask::Run() {
756 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456373 is fixed.
757 tracked_objects::ScopedTracker
tracking_profile(
758 FROM_HERE_WITH_EXPLICIT_FUNCTION(
759 "456373 CookieMonster::SetCookieWithOptionsTask::Run"));
760 bool result
= this->cookie_monster()->SetCookieWithOptions(url_
, cookie_line_
,
762 if (!callback_
.is_null()) {
763 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run
,
764 base::Unretained(&callback_
), result
));
768 // Task class for GetCookiesWithOptions call.
769 class CookieMonster::GetCookiesWithOptionsTask
: public CookieMonsterTask
{
771 GetCookiesWithOptionsTask(CookieMonster
* cookie_monster
,
773 const CookieOptions
& options
,
774 const GetCookiesCallback
& callback
)
775 : CookieMonsterTask(cookie_monster
),
778 callback_(callback
) {}
780 // CookieMonsterTask:
784 ~GetCookiesWithOptionsTask() override
{}
788 CookieOptions options_
;
789 GetCookiesCallback callback_
;
791 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask
);
794 void CookieMonster::GetCookiesWithOptionsTask::Run() {
795 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456373 is fixed.
796 tracked_objects::ScopedTracker
tracking_profile(
797 FROM_HERE_WITH_EXPLICIT_FUNCTION(
798 "456373 CookieMonster::GetCookiesWithOptionsTask::Run"));
800 this->cookie_monster()->GetCookiesWithOptions(url_
, options_
);
801 if (!callback_
.is_null()) {
802 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run
,
803 base::Unretained(&callback_
), cookie
));
807 // Task class for DeleteCookie call.
808 class CookieMonster::DeleteCookieTask
: public DeleteTask
<void> {
810 DeleteCookieTask(CookieMonster
* cookie_monster
,
812 const std::string
& cookie_name
,
813 const base::Closure
& callback
)
814 : DeleteTask
<void>(cookie_monster
, callback
),
816 cookie_name_(cookie_name
) {}
819 void RunDeleteTask() override
;
822 ~DeleteCookieTask() override
{}
826 std::string cookie_name_
;
828 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask
);
831 void CookieMonster::DeleteCookieTask::RunDeleteTask() {
832 this->cookie_monster()->DeleteCookie(url_
, cookie_name_
);
835 // Task class for DeleteSessionCookies call.
836 class CookieMonster::DeleteSessionCookiesTask
: public DeleteTask
<int> {
838 DeleteSessionCookiesTask(CookieMonster
* cookie_monster
,
839 const DeleteCallback
& callback
)
840 : DeleteTask
<int>(cookie_monster
, callback
) {}
843 int RunDeleteTask() override
;
846 ~DeleteSessionCookiesTask() override
{}
849 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask
);
852 int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
853 return this->cookie_monster()->DeleteSessionCookies();
856 // Task class for HasCookiesForETLDP1Task call.
857 class CookieMonster::HasCookiesForETLDP1Task
: public CookieMonsterTask
{
859 HasCookiesForETLDP1Task(CookieMonster
* cookie_monster
,
860 const std::string
& etldp1
,
861 const HasCookiesForETLDP1Callback
& callback
)
862 : CookieMonsterTask(cookie_monster
),
864 callback_(callback
) {}
866 // CookieMonsterTask:
870 ~HasCookiesForETLDP1Task() override
{}
874 HasCookiesForETLDP1Callback callback_
;
876 DISALLOW_COPY_AND_ASSIGN(HasCookiesForETLDP1Task
);
879 void CookieMonster::HasCookiesForETLDP1Task::Run() {
880 bool result
= this->cookie_monster()->HasCookiesForETLDP1(etldp1_
);
881 if (!callback_
.is_null()) {
882 this->InvokeCallback(base::Bind(&HasCookiesForETLDP1Callback::Run
,
883 base::Unretained(&callback_
), result
));
887 // Asynchronous CookieMonster API
889 void CookieMonster::SetCookieWithDetailsAsync(
891 const std::string
& name
,
892 const std::string
& value
,
893 const std::string
& domain
,
894 const std::string
& path
,
895 const Time
& expiration_time
,
898 bool first_party_only
,
899 CookiePriority priority
,
900 const SetCookiesCallback
& callback
) {
901 scoped_refptr
<SetCookieWithDetailsTask
> task
= new SetCookieWithDetailsTask(
902 this, url
, name
, value
, domain
, path
, expiration_time
, secure
, http_only
,
903 first_party_only
, priority
, callback
);
904 DoCookieTaskForURL(task
, url
);
907 void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback
& callback
) {
908 scoped_refptr
<GetAllCookiesTask
> task
= new GetAllCookiesTask(this, callback
);
913 void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
915 const CookieOptions
& options
,
916 const GetCookieListCallback
& callback
) {
917 scoped_refptr
<GetAllCookiesForURLWithOptionsTask
> task
=
918 new GetAllCookiesForURLWithOptionsTask(this, url
, options
, callback
);
920 DoCookieTaskForURL(task
, url
);
923 void CookieMonster::GetAllCookiesForURLAsync(
925 const GetCookieListCallback
& callback
) {
926 CookieOptions options
;
927 options
.set_include_httponly();
928 options
.set_include_first_party_only();
929 scoped_refptr
<GetAllCookiesForURLWithOptionsTask
> task
=
930 new GetAllCookiesForURLWithOptionsTask(this, url
, options
, callback
);
932 DoCookieTaskForURL(task
, url
);
935 void CookieMonster::HasCookiesForETLDP1Async(
936 const std::string
& etldp1
,
937 const HasCookiesForETLDP1Callback
& callback
) {
938 scoped_refptr
<HasCookiesForETLDP1Task
> task
=
939 new HasCookiesForETLDP1Task(this, etldp1
, callback
);
941 DoCookieTaskForURL(task
, GURL("http://" + etldp1
));
944 void CookieMonster::DeleteAllAsync(const DeleteCallback
& callback
) {
945 scoped_refptr
<DeleteAllTask
> task
= new DeleteAllTask(this, callback
);
950 void CookieMonster::DeleteAllCreatedBetweenAsync(
951 const Time
& delete_begin
,
952 const Time
& delete_end
,
953 const DeleteCallback
& callback
) {
954 scoped_refptr
<DeleteAllCreatedBetweenTask
> task
=
955 new DeleteAllCreatedBetweenTask(this, delete_begin
, delete_end
, callback
);
960 void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
961 const Time delete_begin
,
962 const Time delete_end
,
964 const DeleteCallback
& callback
) {
965 scoped_refptr
<DeleteAllCreatedBetweenForHostTask
> task
=
966 new DeleteAllCreatedBetweenForHostTask(this, delete_begin
, delete_end
,
969 DoCookieTaskForURL(task
, url
);
972 void CookieMonster::DeleteAllForHostAsync(const GURL
& url
,
973 const DeleteCallback
& callback
) {
974 scoped_refptr
<DeleteAllForHostTask
> task
=
975 new DeleteAllForHostTask(this, url
, callback
);
977 DoCookieTaskForURL(task
, url
);
980 void CookieMonster::DeleteCanonicalCookieAsync(
981 const CanonicalCookie
& cookie
,
982 const DeleteCookieCallback
& callback
) {
983 scoped_refptr
<DeleteCanonicalCookieTask
> task
=
984 new DeleteCanonicalCookieTask(this, cookie
, callback
);
989 void CookieMonster::SetCookieWithOptionsAsync(
991 const std::string
& cookie_line
,
992 const CookieOptions
& options
,
993 const SetCookiesCallback
& callback
) {
994 scoped_refptr
<SetCookieWithOptionsTask
> task
=
995 new SetCookieWithOptionsTask(this, url
, cookie_line
, options
, callback
);
997 DoCookieTaskForURL(task
, url
);
1000 void CookieMonster::GetCookiesWithOptionsAsync(
1002 const CookieOptions
& options
,
1003 const GetCookiesCallback
& callback
) {
1004 scoped_refptr
<GetCookiesWithOptionsTask
> task
=
1005 new GetCookiesWithOptionsTask(this, url
, options
, callback
);
1007 DoCookieTaskForURL(task
, url
);
1010 void CookieMonster::DeleteCookieAsync(const GURL
& url
,
1011 const std::string
& cookie_name
,
1012 const base::Closure
& callback
) {
1013 scoped_refptr
<DeleteCookieTask
> task
=
1014 new DeleteCookieTask(this, url
, cookie_name
, callback
);
1016 DoCookieTaskForURL(task
, url
);
1019 void CookieMonster::DeleteSessionCookiesAsync(
1020 const CookieStore::DeleteCallback
& callback
) {
1021 scoped_refptr
<DeleteSessionCookiesTask
> task
=
1022 new DeleteSessionCookiesTask(this, callback
);
1027 void CookieMonster::DoCookieTask(
1028 const scoped_refptr
<CookieMonsterTask
>& task_item
) {
1030 base::AutoLock
autolock(lock_
);
1033 tasks_pending_
.push(task_item
);
1041 void CookieMonster::DoCookieTaskForURL(
1042 const scoped_refptr
<CookieMonsterTask
>& task_item
,
1045 base::AutoLock
autolock(lock_
);
1047 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1048 // then run the task, otherwise load from DB.
1050 // Checks if the domain key has been loaded.
1052 cookie_util::GetEffectiveDomain(url
.scheme(), url
.host()));
1053 if (keys_loaded_
.find(key
) == keys_loaded_
.end()) {
1054 std::map
<std::string
,
1055 std::deque
<scoped_refptr
<CookieMonsterTask
>>>::iterator it
=
1056 tasks_pending_for_key_
.find(key
);
1057 if (it
== tasks_pending_for_key_
.end()) {
1058 store_
->LoadCookiesForKey(
1059 key
, base::Bind(&CookieMonster::OnKeyLoaded
, this, key
));
1060 it
= tasks_pending_for_key_
1061 .insert(std::make_pair(
1062 key
, std::deque
<scoped_refptr
<CookieMonsterTask
>>()))
1065 it
->second
.push_back(task_item
);
1073 bool CookieMonster::SetCookieWithDetails(const GURL
& url
,
1074 const std::string
& name
,
1075 const std::string
& value
,
1076 const std::string
& domain
,
1077 const std::string
& path
,
1078 const base::Time
& expiration_time
,
1081 bool first_party_only
,
1082 CookiePriority priority
) {
1083 base::AutoLock
autolock(lock_
);
1085 if (!HasCookieableScheme(url
))
1088 Time creation_time
= CurrentTime();
1089 last_time_seen_
= creation_time
;
1091 scoped_ptr
<CanonicalCookie
> cc
;
1092 cc
.reset(CanonicalCookie::Create(url
, name
, value
, domain
, path
,
1093 creation_time
, expiration_time
, secure
,
1094 http_only
, first_party_only
, priority
));
1099 CookieOptions options
;
1100 options
.set_include_httponly();
1101 options
.set_include_first_party_only();
1102 return SetCanonicalCookie(&cc
, creation_time
, options
);
1105 bool CookieMonster::ImportCookies(const CookieList
& list
) {
1106 base::AutoLock
autolock(lock_
);
1108 for (net::CookieList::const_iterator iter
= list
.begin(); iter
!= list
.end();
1110 scoped_ptr
<CanonicalCookie
> cookie(new CanonicalCookie(*iter
));
1111 net::CookieOptions options
;
1112 options
.set_include_httponly();
1113 options
.set_include_first_party_only();
1114 if (!SetCanonicalCookie(&cookie
, cookie
->CreationDate(), options
))
1120 CookieList
CookieMonster::GetAllCookies() {
1121 base::AutoLock
autolock(lock_
);
1123 // This function is being called to scrape the cookie list for management UI
1124 // or similar. We shouldn't show expired cookies in this list since it will
1125 // just be confusing to users, and this function is called rarely enough (and
1126 // is already slow enough) that it's OK to take the time to garbage collect
1127 // the expired cookies now.
1129 // Note that this does not prune cookies to be below our limits (if we've
1130 // exceeded them) the way that calling GarbageCollect() would.
1131 GarbageCollectExpired(
1132 Time::Now(), CookieMapItPair(cookies_
.begin(), cookies_
.end()), NULL
);
1134 // Copy the CanonicalCookie pointers from the map so that we can use the same
1135 // sorter as elsewhere, then copy the result out.
1136 std::vector
<CanonicalCookie
*> cookie_ptrs
;
1137 cookie_ptrs
.reserve(cookies_
.size());
1138 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end(); ++it
)
1139 cookie_ptrs
.push_back(it
->second
);
1140 std::sort(cookie_ptrs
.begin(), cookie_ptrs
.end(), CookieSorter
);
1142 CookieList cookie_list
;
1143 cookie_list
.reserve(cookie_ptrs
.size());
1144 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookie_ptrs
.begin();
1145 it
!= cookie_ptrs
.end(); ++it
)
1146 cookie_list
.push_back(**it
);
1151 CookieList
CookieMonster::GetAllCookiesForURLWithOptions(
1153 const CookieOptions
& options
) {
1154 base::AutoLock
autolock(lock_
);
1156 std::vector
<CanonicalCookie
*> cookie_ptrs
;
1157 FindCookiesForHostAndDomain(url
, options
, false, &cookie_ptrs
);
1158 std::sort(cookie_ptrs
.begin(), cookie_ptrs
.end(), CookieSorter
);
1161 cookies
.reserve(cookie_ptrs
.size());
1162 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookie_ptrs
.begin();
1163 it
!= cookie_ptrs
.end(); it
++)
1164 cookies
.push_back(**it
);
1169 CookieList
CookieMonster::GetAllCookiesForURL(const GURL
& url
) {
1170 CookieOptions options
;
1171 options
.set_include_httponly();
1172 options
.set_first_party_url(url
);
1174 return GetAllCookiesForURLWithOptions(url
, options
);
1177 int CookieMonster::DeleteAll(bool sync_to_store
) {
1178 base::AutoLock
autolock(lock_
);
1180 int num_deleted
= 0;
1181 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1182 CookieMap::iterator curit
= it
;
1184 InternalDeleteCookie(curit
, sync_to_store
,
1186 ? DELETE_COOKIE_EXPLICIT
1187 : DELETE_COOKIE_DONT_RECORD
/* Destruction. */);
1194 int CookieMonster::DeleteAllCreatedBetween(const Time
& delete_begin
,
1195 const Time
& delete_end
) {
1196 base::AutoLock
autolock(lock_
);
1198 int num_deleted
= 0;
1199 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1200 CookieMap::iterator curit
= it
;
1201 CanonicalCookie
* cc
= curit
->second
;
1204 if (cc
->CreationDate() >= delete_begin
&&
1205 (delete_end
.is_null() || cc
->CreationDate() < delete_end
)) {
1206 InternalDeleteCookie(curit
, true, /*sync_to_store*/
1207 DELETE_COOKIE_EXPLICIT
);
1215 int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin
,
1216 const Time delete_end
,
1218 base::AutoLock
autolock(lock_
);
1220 if (!HasCookieableScheme(url
))
1223 const std::string
host(url
.host());
1225 // We store host cookies in the store by their canonical host name;
1226 // domain cookies are stored with a leading ".". So this is a pretty
1227 // simple lookup and per-cookie delete.
1228 int num_deleted
= 0;
1229 for (CookieMapItPair its
= cookies_
.equal_range(GetKey(host
));
1230 its
.first
!= its
.second
;) {
1231 CookieMap::iterator curit
= its
.first
;
1234 const CanonicalCookie
* const cc
= curit
->second
;
1236 // Delete only on a match as a host cookie.
1237 if (cc
->IsHostCookie() && cc
->IsDomainMatch(host
) &&
1238 cc
->CreationDate() >= delete_begin
&&
1239 // The assumption that null |delete_end| is equivalent to
1240 // Time::Max() is confusing.
1241 (delete_end
.is_null() || cc
->CreationDate() < delete_end
)) {
1244 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPLICIT
);
1250 int CookieMonster::DeleteAllForHost(const GURL
& url
) {
1251 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url
);
1254 bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie
& cookie
) {
1255 base::AutoLock
autolock(lock_
);
1257 for (CookieMapItPair its
= cookies_
.equal_range(GetKey(cookie
.Domain()));
1258 its
.first
!= its
.second
; ++its
.first
) {
1259 // The creation date acts as our unique index...
1260 if (its
.first
->second
->CreationDate() == cookie
.CreationDate()) {
1261 InternalDeleteCookie(its
.first
, true, DELETE_COOKIE_EXPLICIT
);
1268 void CookieMonster::SetCookieableSchemes(const char* const schemes
[],
1269 size_t num_schemes
) {
1270 base::AutoLock
autolock(lock_
);
1272 // Cookieable Schemes must be set before first use of function.
1273 DCHECK(!initialized_
);
1275 cookieable_schemes_
.clear();
1276 cookieable_schemes_
.insert(cookieable_schemes_
.end(), schemes
,
1277 schemes
+ num_schemes
);
1280 void CookieMonster::SetEnableFileScheme(bool accept
) {
1281 // This assumes "file" is always at the end of the array. See the comment
1282 // above kDefaultCookieableSchemes.
1283 int num_schemes
= accept
? kDefaultCookieableSchemesCount
1284 : kDefaultCookieableSchemesCount
- 1;
1285 SetCookieableSchemes(kDefaultCookieableSchemes
, num_schemes
);
1288 void CookieMonster::SetKeepExpiredCookies() {
1289 keep_expired_cookies_
= true;
1292 void CookieMonster::FlushStore(const base::Closure
& callback
) {
1293 base::AutoLock
autolock(lock_
);
1294 if (initialized_
&& store_
.get())
1295 store_
->Flush(callback
);
1296 else if (!callback
.is_null())
1297 base::MessageLoop::current()->PostTask(FROM_HERE
, callback
);
1300 bool CookieMonster::SetCookieWithOptions(const GURL
& url
,
1301 const std::string
& cookie_line
,
1302 const CookieOptions
& options
) {
1303 base::AutoLock
autolock(lock_
);
1305 if (!HasCookieableScheme(url
)) {
1309 return SetCookieWithCreationTimeAndOptions(url
, cookie_line
, Time(), options
);
1312 std::string
CookieMonster::GetCookiesWithOptions(const GURL
& url
,
1313 const CookieOptions
& options
) {
1314 base::AutoLock
autolock(lock_
);
1316 if (!HasCookieableScheme(url
))
1317 return std::string();
1319 std::vector
<CanonicalCookie
*> cookies
;
1320 FindCookiesForHostAndDomain(url
, options
, true, &cookies
);
1321 std::sort(cookies
.begin(), cookies
.end(), CookieSorter
);
1323 std::string cookie_line
= BuildCookieLine(cookies
);
1325 VLOG(kVlogGetCookies
) << "GetCookies() result: " << cookie_line
;
1330 void CookieMonster::DeleteCookie(const GURL
& url
,
1331 const std::string
& cookie_name
) {
1332 base::AutoLock
autolock(lock_
);
1334 if (!HasCookieableScheme(url
))
1337 CookieOptions options
;
1338 options
.set_include_httponly();
1339 options
.set_include_first_party_only();
1340 // Get the cookies for this host and its domain(s).
1341 std::vector
<CanonicalCookie
*> cookies
;
1342 FindCookiesForHostAndDomain(url
, options
, true, &cookies
);
1343 std::set
<CanonicalCookie
*> matching_cookies
;
1345 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookies
.begin();
1346 it
!= cookies
.end(); ++it
) {
1347 if ((*it
)->Name() != cookie_name
)
1349 if (url
.path().find((*it
)->Path()))
1351 matching_cookies
.insert(*it
);
1354 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1355 CookieMap::iterator curit
= it
;
1357 if (matching_cookies
.find(curit
->second
) != matching_cookies
.end()) {
1358 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPLICIT
);
1363 int CookieMonster::DeleteSessionCookies() {
1364 base::AutoLock
autolock(lock_
);
1366 int num_deleted
= 0;
1367 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1368 CookieMap::iterator curit
= it
;
1369 CanonicalCookie
* cc
= curit
->second
;
1372 if (!cc
->IsPersistent()) {
1373 InternalDeleteCookie(curit
, true, /*sync_to_store*/
1374 DELETE_COOKIE_EXPIRED
);
1382 bool CookieMonster::HasCookiesForETLDP1(const std::string
& etldp1
) {
1383 base::AutoLock
autolock(lock_
);
1385 const std::string
key(GetKey(etldp1
));
1387 CookieMapItPair its
= cookies_
.equal_range(key
);
1388 return its
.first
!= its
.second
;
1391 CookieMonster
* CookieMonster::GetCookieMonster() {
1395 // This function must be called before the CookieMonster is used.
1396 void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies
) {
1397 DCHECK(!initialized_
);
1398 persist_session_cookies_
= persist_session_cookies
;
1401 void CookieMonster::SetForceKeepSessionState() {
1403 store_
->SetForceKeepSessionState();
1407 CookieMonster::~CookieMonster() {
1411 bool CookieMonster::SetCookieWithCreationTime(const GURL
& url
,
1412 const std::string
& cookie_line
,
1413 const base::Time
& creation_time
) {
1414 DCHECK(!store_
.get()) << "This method is only to be used by unit-tests.";
1415 base::AutoLock
autolock(lock_
);
1417 if (!HasCookieableScheme(url
)) {
1422 return SetCookieWithCreationTimeAndOptions(url
, cookie_line
, creation_time
,
1426 void CookieMonster::InitStore() {
1427 DCHECK(store_
.get()) << "Store must exist to initialize";
1429 // We bind in the current time so that we can report the wall-clock time for
1431 store_
->Load(base::Bind(&CookieMonster::OnLoaded
, this, TimeTicks::Now()));
1434 void CookieMonster::ReportLoaded() {
1435 if (delegate_
.get())
1436 delegate_
->OnLoaded();
1439 void CookieMonster::OnLoaded(TimeTicks beginning_time
,
1440 const std::vector
<CanonicalCookie
*>& cookies
) {
1441 StoreLoadedCookies(cookies
);
1442 histogram_time_blocked_on_load_
->AddTime(TimeTicks::Now() - beginning_time
);
1444 // Invoke the task queue of cookie request.
1450 void CookieMonster::OnKeyLoaded(const std::string
& key
,
1451 const std::vector
<CanonicalCookie
*>& cookies
) {
1452 // This function does its own separate locking.
1453 StoreLoadedCookies(cookies
);
1455 std::deque
<scoped_refptr
<CookieMonsterTask
>> tasks_pending_for_key
;
1457 // We need to do this repeatedly until no more tasks were added to the queue
1458 // during the period where we release the lock.
1461 base::AutoLock
autolock(lock_
);
1462 std::map
<std::string
,
1463 std::deque
<scoped_refptr
<CookieMonsterTask
>>>::iterator it
=
1464 tasks_pending_for_key_
.find(key
);
1465 if (it
== tasks_pending_for_key_
.end()) {
1466 keys_loaded_
.insert(key
);
1469 if (it
->second
.empty()) {
1470 keys_loaded_
.insert(key
);
1471 tasks_pending_for_key_
.erase(it
);
1474 it
->second
.swap(tasks_pending_for_key
);
1477 while (!tasks_pending_for_key
.empty()) {
1478 scoped_refptr
<CookieMonsterTask
> task
= tasks_pending_for_key
.front();
1480 tasks_pending_for_key
.pop_front();
1485 void CookieMonster::StoreLoadedCookies(
1486 const std::vector
<CanonicalCookie
*>& cookies
) {
1487 // Initialize the store and sync in any saved persistent cookies. We don't
1488 // care if it's expired, insert it so it can be garbage collected, removed,
1490 base::AutoLock
autolock(lock_
);
1492 CookieItVector cookies_with_control_chars
;
1494 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookies
.begin();
1495 it
!= cookies
.end(); ++it
) {
1496 int64 cookie_creation_time
= (*it
)->CreationDate().ToInternalValue();
1498 if (creation_times_
.insert(cookie_creation_time
).second
) {
1499 CookieMap::iterator inserted
=
1500 InternalInsertCookie(GetKey((*it
)->Domain()), *it
, false);
1501 const Time
cookie_access_time((*it
)->LastAccessDate());
1502 if (earliest_access_time_
.is_null() ||
1503 cookie_access_time
< earliest_access_time_
)
1504 earliest_access_time_
= cookie_access_time
;
1506 if (ContainsControlCharacter((*it
)->Name()) ||
1507 ContainsControlCharacter((*it
)->Value())) {
1508 cookies_with_control_chars
.push_back(inserted
);
1511 LOG(ERROR
) << base::StringPrintf(
1512 "Found cookies with duplicate creation "
1513 "times in backing store: "
1514 "{name='%s', domain='%s', path='%s'}",
1515 (*it
)->Name().c_str(), (*it
)->Domain().c_str(),
1516 (*it
)->Path().c_str());
1517 // We've been given ownership of the cookie and are throwing it
1518 // away; reclaim the space.
1523 // Any cookies that contain control characters that we have loaded from the
1524 // persistent store should be deleted. See http://crbug.com/238041.
1525 for (CookieItVector::iterator it
= cookies_with_control_chars
.begin();
1526 it
!= cookies_with_control_chars
.end();) {
1527 CookieItVector::iterator curit
= it
;
1530 InternalDeleteCookie(*curit
, true, DELETE_COOKIE_CONTROL_CHAR
);
1533 // After importing cookies from the PersistentCookieStore, verify that
1534 // none of our other constraints are violated.
1535 // In particular, the backing store might have given us duplicate cookies.
1537 // This method could be called multiple times due to priority loading, thus
1538 // cookies loaded in previous runs will be validated again, but this is OK
1539 // since they are expected to be much fewer than total DB.
1540 EnsureCookiesMapIsValid();
1543 void CookieMonster::InvokeQueue() {
1545 scoped_refptr
<CookieMonsterTask
> request_task
;
1547 base::AutoLock
autolock(lock_
);
1548 if (tasks_pending_
.empty()) {
1550 creation_times_
.clear();
1551 keys_loaded_
.clear();
1554 request_task
= tasks_pending_
.front();
1555 tasks_pending_
.pop();
1557 request_task
->Run();
1561 void CookieMonster::EnsureCookiesMapIsValid() {
1562 lock_
.AssertAcquired();
1564 int num_duplicates_trimmed
= 0;
1566 // Iterate through all the of the cookies, grouped by host.
1567 CookieMap::iterator prev_range_end
= cookies_
.begin();
1568 while (prev_range_end
!= cookies_
.end()) {
1569 CookieMap::iterator cur_range_begin
= prev_range_end
;
1570 const std::string key
= cur_range_begin
->first
; // Keep a copy.
1571 CookieMap::iterator cur_range_end
= cookies_
.upper_bound(key
);
1572 prev_range_end
= cur_range_end
;
1574 // Ensure no equivalent cookies for this host.
1575 num_duplicates_trimmed
+=
1576 TrimDuplicateCookiesForKey(key
, cur_range_begin
, cur_range_end
);
1579 // Record how many duplicates were found in the database.
1580 // See InitializeHistograms() for details.
1581 histogram_cookie_deletion_cause_
->Add(num_duplicates_trimmed
);
1584 int CookieMonster::TrimDuplicateCookiesForKey(const std::string
& key
,
1585 CookieMap::iterator begin
,
1586 CookieMap::iterator end
) {
1587 lock_
.AssertAcquired();
1589 // Set of cookies ordered by creation time.
1590 typedef std::set
<CookieMap::iterator
, OrderByCreationTimeDesc
> CookieSet
;
1592 // Helper map we populate to find the duplicates.
1593 typedef std::map
<CookieSignature
, CookieSet
> EquivalenceMap
;
1594 EquivalenceMap equivalent_cookies
;
1596 // The number of duplicate cookies that have been found.
1597 int num_duplicates
= 0;
1599 // Iterate through all of the cookies in our range, and insert them into
1600 // the equivalence map.
1601 for (CookieMap::iterator it
= begin
; it
!= end
; ++it
) {
1602 DCHECK_EQ(key
, it
->first
);
1603 CanonicalCookie
* cookie
= it
->second
;
1605 CookieSignature
signature(cookie
->Name(), cookie
->Domain(), cookie
->Path());
1606 CookieSet
& set
= equivalent_cookies
[signature
];
1608 // We found a duplicate!
1612 // We save the iterator into |cookies_| rather than the actual cookie
1613 // pointer, since we may need to delete it later.
1614 bool insert_success
= set
.insert(it
).second
;
1615 DCHECK(insert_success
)
1616 << "Duplicate creation times found in duplicate cookie name scan.";
1619 // If there were no duplicates, we are done!
1620 if (num_duplicates
== 0)
1623 // Make sure we find everything below that we did above.
1624 int num_duplicates_found
= 0;
1626 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1627 // and from the backing store.
1628 for (EquivalenceMap::iterator it
= equivalent_cookies
.begin();
1629 it
!= equivalent_cookies
.end(); ++it
) {
1630 const CookieSignature
& signature
= it
->first
;
1631 CookieSet
& dupes
= it
->second
;
1633 if (dupes
.size() <= 1)
1634 continue; // This cookiename/path has no duplicates.
1635 num_duplicates_found
+= dupes
.size() - 1;
1637 // Since |dups| is sorted by creation time (descending), the first cookie
1638 // is the most recent one, so we will keep it. The rest are duplicates.
1639 dupes
.erase(dupes
.begin());
1641 LOG(ERROR
) << base::StringPrintf(
1642 "Found %d duplicate cookies for host='%s', "
1643 "with {name='%s', domain='%s', path='%s'}",
1644 static_cast<int>(dupes
.size()), key
.c_str(), signature
.name
.c_str(),
1645 signature
.domain
.c_str(), signature
.path
.c_str());
1647 // Remove all the cookies identified by |dupes|. It is valid to delete our
1648 // list of iterators one at a time, since |cookies_| is a multimap (they
1649 // don't invalidate existing iterators following deletion).
1650 for (CookieSet::iterator dupes_it
= dupes
.begin(); dupes_it
!= dupes
.end();
1652 InternalDeleteCookie(*dupes_it
, true,
1653 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
);
1656 DCHECK_EQ(num_duplicates
, num_duplicates_found
);
1658 return num_duplicates
;
1661 // Note: file must be the last scheme.
1662 const char* const CookieMonster::kDefaultCookieableSchemes
[] = {"http",
1667 const int CookieMonster::kDefaultCookieableSchemesCount
=
1668 arraysize(kDefaultCookieableSchemes
);
1670 void CookieMonster::SetDefaultCookieableSchemes() {
1671 // Always disable file scheme unless SetEnableFileScheme(true) is called.
1672 SetCookieableSchemes(kDefaultCookieableSchemes
,
1673 kDefaultCookieableSchemesCount
- 1);
1676 void CookieMonster::FindCookiesForHostAndDomain(
1678 const CookieOptions
& options
,
1679 bool update_access_time
,
1680 std::vector
<CanonicalCookie
*>* cookies
) {
1681 lock_
.AssertAcquired();
1683 const Time
current_time(CurrentTime());
1685 // Probe to save statistics relatively frequently. We do it here rather
1686 // than in the set path as many websites won't set cookies, and we
1687 // want to collect statistics whenever the browser's being used.
1688 RecordPeriodicStats(current_time
);
1690 // Can just dispatch to FindCookiesForKey
1691 const std::string
key(GetKey(url
.host()));
1692 FindCookiesForKey(key
, url
, options
, current_time
, update_access_time
,
1696 void CookieMonster::FindCookiesForKey(const std::string
& key
,
1698 const CookieOptions
& options
,
1699 const Time
& current
,
1700 bool update_access_time
,
1701 std::vector
<CanonicalCookie
*>* cookies
) {
1702 lock_
.AssertAcquired();
1704 for (CookieMapItPair its
= cookies_
.equal_range(key
);
1705 its
.first
!= its
.second
;) {
1706 CookieMap::iterator curit
= its
.first
;
1707 CanonicalCookie
* cc
= curit
->second
;
1710 // If the cookie is expired, delete it.
1711 if (cc
->IsExpired(current
) && !keep_expired_cookies_
) {
1712 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPIRED
);
1716 // Filter out cookies that should not be included for a request to the
1717 // given |url|. HTTP only cookies are filtered depending on the passed
1718 // cookie |options|.
1719 if (!cc
->IncludeForRequestURL(url
, options
))
1722 // Add this cookie to the set of matching cookies. Update the access
1723 // time if we've been requested to do so.
1724 if (update_access_time
) {
1725 InternalUpdateCookieAccessTime(cc
, current
);
1727 cookies
->push_back(cc
);
1731 bool CookieMonster::DeleteAnyEquivalentCookie(const std::string
& key
,
1732 const CanonicalCookie
& ecc
,
1734 bool already_expired
) {
1735 lock_
.AssertAcquired();
1737 bool found_equivalent_cookie
= false;
1738 bool skipped_httponly
= false;
1739 for (CookieMapItPair its
= cookies_
.equal_range(key
);
1740 its
.first
!= its
.second
;) {
1741 CookieMap::iterator curit
= its
.first
;
1742 CanonicalCookie
* cc
= curit
->second
;
1745 if (ecc
.IsEquivalent(*cc
)) {
1746 // We should never have more than one equivalent cookie, since they should
1747 // overwrite each other.
1748 CHECK(!found_equivalent_cookie
)
1749 << "Duplicate equivalent cookies found, cookie store is corrupted.";
1750 if (skip_httponly
&& cc
->IsHttpOnly()) {
1751 skipped_httponly
= true;
1753 InternalDeleteCookie(curit
, true, already_expired
1754 ? DELETE_COOKIE_EXPIRED_OVERWRITE
1755 : DELETE_COOKIE_OVERWRITE
);
1757 found_equivalent_cookie
= true;
1760 return skipped_httponly
;
1763 CookieMonster::CookieMap::iterator
CookieMonster::InternalInsertCookie(
1764 const std::string
& key
,
1765 CanonicalCookie
* cc
,
1766 bool sync_to_store
) {
1767 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456373 is fixed.
1768 tracked_objects::ScopedTracker
tracking_profile(
1769 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1770 "456373 CookieMonster::InternalInsertCookie"));
1771 lock_
.AssertAcquired();
1773 if ((cc
->IsPersistent() || persist_session_cookies_
) && store_
.get() &&
1775 store_
->AddCookie(*cc
);
1776 CookieMap::iterator inserted
=
1777 cookies_
.insert(CookieMap::value_type(key
, cc
));
1778 if (delegate_
.get()) {
1779 delegate_
->OnCookieChanged(*cc
, false,
1780 CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
);
1782 RunCallbacks(*cc
, false);
1787 bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1789 const std::string
& cookie_line
,
1790 const Time
& creation_time_or_null
,
1791 const CookieOptions
& options
) {
1792 lock_
.AssertAcquired();
1794 VLOG(kVlogSetCookies
) << "SetCookie() line: " << cookie_line
;
1796 Time creation_time
= creation_time_or_null
;
1797 if (creation_time
.is_null()) {
1798 creation_time
= CurrentTime();
1799 last_time_seen_
= creation_time
;
1802 scoped_ptr
<CanonicalCookie
> cc(
1803 CanonicalCookie::Create(url
, cookie_line
, creation_time
, options
));
1806 VLOG(kVlogSetCookies
) << "WARNING: Failed to allocate CanonicalCookie";
1809 return SetCanonicalCookie(&cc
, creation_time
, options
);
1812 bool CookieMonster::SetCanonicalCookie(scoped_ptr
<CanonicalCookie
>* cc
,
1813 const Time
& creation_time
,
1814 const CookieOptions
& options
) {
1815 const std::string
key(GetKey((*cc
)->Domain()));
1816 bool already_expired
= (*cc
)->IsExpired(creation_time
);
1818 if (DeleteAnyEquivalentCookie(key
, **cc
, options
.exclude_httponly(),
1820 VLOG(kVlogSetCookies
) << "SetCookie() not clobbering httponly cookie";
1824 VLOG(kVlogSetCookies
) << "SetCookie() key: " << key
1825 << " cc: " << (*cc
)->DebugString();
1827 // Realize that we might be setting an expired cookie, and the only point
1828 // was to delete the cookie which we've already done.
1829 if (!already_expired
|| keep_expired_cookies_
) {
1830 // See InitializeHistograms() for details.
1831 if ((*cc
)->IsPersistent()) {
1832 histogram_expiration_duration_minutes_
->Add(
1833 ((*cc
)->ExpiryDate() - creation_time
).InMinutes());
1837 CanonicalCookie cookie
= *(cc
->get());
1838 InternalInsertCookie(key
, cc
->release(), true);
1841 VLOG(kVlogSetCookies
) << "SetCookie() not storing already expired cookie.";
1844 // We assume that hopefully setting a cookie will be less common than
1845 // querying a cookie. Since setting a cookie can put us over our limits,
1846 // make sure that we garbage collect... We can also make the assumption that
1847 // if a cookie was set, in the common case it will be used soon after,
1848 // and we will purge the expired cookies in GetCookies().
1849 GarbageCollect(creation_time
, key
);
1854 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie
* cc
,
1855 const Time
& current
) {
1856 lock_
.AssertAcquired();
1858 // Based off the Mozilla code. When a cookie has been accessed recently,
1859 // don't bother updating its access time again. This reduces the number of
1860 // updates we do during pageload, which in turn reduces the chance our storage
1861 // backend will hit its batch thresholds and be forced to update.
1862 if ((current
- cc
->LastAccessDate()) < last_access_threshold_
)
1865 // See InitializeHistograms() for details.
1866 histogram_between_access_interval_minutes_
->Add(
1867 (current
- cc
->LastAccessDate()).InMinutes());
1869 cc
->SetLastAccessDate(current
);
1870 if ((cc
->IsPersistent() || persist_session_cookies_
) && store_
.get())
1871 store_
->UpdateCookieAccessTime(*cc
);
1874 // InternalDeleteCookies must not invalidate iterators other than the one being
1876 void CookieMonster::InternalDeleteCookie(CookieMap::iterator it
,
1878 DeletionCause deletion_cause
) {
1879 lock_
.AssertAcquired();
1881 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1882 // but DeletionCause's visibility (or lack thereof) forces us to make
1884 static_assert(arraysize(ChangeCauseMapping
) == DELETE_COOKIE_LAST_ENTRY
+ 1,
1885 "ChangeCauseMapping size should match DeletionCause size");
1887 // See InitializeHistograms() for details.
1888 if (deletion_cause
!= DELETE_COOKIE_DONT_RECORD
)
1889 histogram_cookie_deletion_cause_
->Add(deletion_cause
);
1891 CanonicalCookie
* cc
= it
->second
;
1892 VLOG(kVlogSetCookies
) << "InternalDeleteCookie() cc: " << cc
->DebugString();
1894 if ((cc
->IsPersistent() || persist_session_cookies_
) && store_
.get() &&
1896 store_
->DeleteCookie(*cc
);
1897 if (delegate_
.get()) {
1898 ChangeCausePair mapping
= ChangeCauseMapping
[deletion_cause
];
1901 delegate_
->OnCookieChanged(*cc
, true, mapping
.cause
);
1903 RunCallbacks(*cc
, true);
1908 // Domain expiry behavior is unchanged by key/expiry scheme (the
1909 // meaning of the key is different, but that's not visible to this routine).
1910 int CookieMonster::GarbageCollect(const Time
& current
, const std::string
& key
) {
1911 lock_
.AssertAcquired();
1913 int num_deleted
= 0;
1914 Time
safe_date(Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays
));
1916 // Collect garbage for this key, minding cookie priorities.
1917 if (cookies_
.count(key
) > kDomainMaxCookies
) {
1918 VLOG(kVlogGarbageCollection
) << "GarbageCollect() key: " << key
;
1920 CookieItVector cookie_its
;
1922 GarbageCollectExpired(current
, cookies_
.equal_range(key
), &cookie_its
);
1923 if (cookie_its
.size() > kDomainMaxCookies
) {
1924 VLOG(kVlogGarbageCollection
) << "Deep Garbage Collect domain.";
1926 cookie_its
.size() - (kDomainMaxCookies
- kDomainPurgeCookies
);
1927 DCHECK(purge_goal
> kDomainPurgeCookies
);
1929 // Boundary iterators into |cookie_its| for different priorities.
1930 CookieItVector::iterator it_bdd
[4];
1931 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
1932 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
1933 it_bdd
[0] = cookie_its
.begin();
1934 it_bdd
[3] = cookie_its
.end();
1936 PartitionCookieByPriority(it_bdd
[0], it_bdd
[3], COOKIE_PRIORITY_LOW
);
1937 it_bdd
[2] = PartitionCookieByPriority(it_bdd
[1], it_bdd
[3],
1938 COOKIE_PRIORITY_MEDIUM
);
1939 size_t quota
[3] = {kDomainCookiesQuotaLow
,
1940 kDomainCookiesQuotaMedium
,
1941 kDomainCookiesQuotaHigh
};
1943 // Purge domain cookies in 3 rounds.
1944 // Round 1: consider low-priority cookies only: evict least-recently
1945 // accessed, while protecting quota[0] of these from deletion.
1946 // Round 2: consider {low, medium}-priority cookies, evict least-recently
1947 // accessed, while protecting quota[0] + quota[1].
1948 // Round 3: consider all cookies, evict least-recently accessed.
1949 size_t accumulated_quota
= 0;
1950 CookieItVector::iterator it_purge_begin
= it_bdd
[0];
1951 for (int i
= 0; i
< 3 && purge_goal
> 0; ++i
) {
1952 accumulated_quota
+= quota
[i
];
1954 size_t num_considered
= it_bdd
[i
+ 1] - it_purge_begin
;
1955 if (num_considered
<= accumulated_quota
)
1958 // Number of cookies that will be purged in this round.
1960 std::min(purge_goal
, num_considered
- accumulated_quota
);
1961 purge_goal
-= round_goal
;
1963 SortLeastRecentlyAccessed(it_purge_begin
, it_bdd
[i
+ 1], round_goal
);
1964 // Cookies accessed on or after |safe_date| would have been safe from
1965 // global purge, and we want to keep track of this.
1966 CookieItVector::iterator it_purge_end
= it_purge_begin
+ round_goal
;
1967 CookieItVector::iterator it_purge_middle
=
1968 LowerBoundAccessDate(it_purge_begin
, it_purge_end
, safe_date
);
1969 // Delete cookies accessed before |safe_date|.
1970 num_deleted
+= GarbageCollectDeleteRange(
1971 current
, DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
, it_purge_begin
,
1973 // Delete cookies accessed on or after |safe_date|.
1974 num_deleted
+= GarbageCollectDeleteRange(
1975 current
, DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
, it_purge_middle
,
1977 it_purge_begin
= it_purge_end
;
1979 DCHECK_EQ(0U, purge_goal
);
1983 // Collect garbage for everything. With firefox style we want to preserve
1984 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
1985 if (cookies_
.size() > kMaxCookies
&& earliest_access_time_
< safe_date
) {
1986 VLOG(kVlogGarbageCollection
) << "GarbageCollect() everything";
1987 CookieItVector cookie_its
;
1988 num_deleted
+= GarbageCollectExpired(
1989 current
, CookieMapItPair(cookies_
.begin(), cookies_
.end()),
1991 if (cookie_its
.size() > kMaxCookies
) {
1992 VLOG(kVlogGarbageCollection
) << "Deep Garbage Collect everything.";
1993 size_t purge_goal
= cookie_its
.size() - (kMaxCookies
- kPurgeCookies
);
1994 DCHECK(purge_goal
> kPurgeCookies
);
1995 // Sorts up to *and including* |cookie_its[purge_goal]|, so
1996 // |earliest_access_time| will be properly assigned even if
1997 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
1998 SortLeastRecentlyAccessed(cookie_its
.begin(), cookie_its
.end(),
2000 // Find boundary to cookies older than safe_date.
2001 CookieItVector::iterator global_purge_it
= LowerBoundAccessDate(
2002 cookie_its
.begin(), cookie_its
.begin() + purge_goal
, safe_date
);
2003 // Only delete the old cookies.
2005 GarbageCollectDeleteRange(current
, DELETE_COOKIE_EVICTED_GLOBAL
,
2006 cookie_its
.begin(), global_purge_it
);
2007 // Set access day to the oldest cookie that wasn't deleted.
2008 earliest_access_time_
= (*global_purge_it
)->second
->LastAccessDate();
2015 int CookieMonster::GarbageCollectExpired(const Time
& current
,
2016 const CookieMapItPair
& itpair
,
2017 CookieItVector
* cookie_its
) {
2018 if (keep_expired_cookies_
)
2021 lock_
.AssertAcquired();
2023 int num_deleted
= 0;
2024 for (CookieMap::iterator it
= itpair
.first
, end
= itpair
.second
; it
!= end
;) {
2025 CookieMap::iterator curit
= it
;
2028 if (curit
->second
->IsExpired(current
)) {
2029 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPIRED
);
2031 } else if (cookie_its
) {
2032 cookie_its
->push_back(curit
);
2039 int CookieMonster::GarbageCollectDeleteRange(const Time
& current
,
2040 DeletionCause cause
,
2041 CookieItVector::iterator it_begin
,
2042 CookieItVector::iterator it_end
) {
2043 for (CookieItVector::iterator it
= it_begin
; it
!= it_end
; it
++) {
2044 histogram_evicted_last_access_minutes_
->Add(
2045 (current
- (*it
)->second
->LastAccessDate()).InMinutes());
2046 InternalDeleteCookie((*it
), true, cause
);
2048 return it_end
- it_begin
;
2051 // A wrapper around registry_controlled_domains::GetDomainAndRegistry
2052 // to make clear we're creating a key for our local map. Here and
2053 // in FindCookiesForHostAndDomain() are the only two places where
2054 // we need to conditionalize based on key type.
2056 // Note that this key algorithm explicitly ignores the scheme. This is
2057 // because when we're entering cookies into the map from the backing store,
2058 // we in general won't have the scheme at that point.
2059 // In practical terms, this means that file cookies will be stored
2060 // in the map either by an empty string or by UNC name (and will be
2061 // limited by kMaxCookiesPerHost), and extension cookies will be stored
2062 // based on the single extension id, as the extension id won't have the
2063 // form of a DNS host and hence GetKey() will return it unchanged.
2065 // Arguably the right thing to do here is to make the key
2066 // algorithm dependent on the scheme, and make sure that the scheme is
2067 // available everywhere the key must be obtained (specfically at backing
2068 // store load time). This would require either changing the backing store
2069 // database schema to include the scheme (far more trouble than it's worth), or
2070 // separating out file cookies into their own CookieMonster instance and
2071 // thus restricting each scheme to a single cookie monster (which might
2072 // be worth it, but is still too much trouble to solve what is currently a
2074 std::string
CookieMonster::GetKey(const std::string
& domain
) const {
2075 std::string
effective_domain(
2076 registry_controlled_domains::GetDomainAndRegistry(
2077 domain
, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
));
2078 if (effective_domain
.empty())
2079 effective_domain
= domain
;
2081 if (!effective_domain
.empty() && effective_domain
[0] == '.')
2082 return effective_domain
.substr(1);
2083 return effective_domain
;
2086 bool CookieMonster::IsCookieableScheme(const std::string
& scheme
) {
2087 base::AutoLock
autolock(lock_
);
2089 return std::find(cookieable_schemes_
.begin(), cookieable_schemes_
.end(),
2090 scheme
) != cookieable_schemes_
.end();
2093 bool CookieMonster::HasCookieableScheme(const GURL
& url
) {
2094 lock_
.AssertAcquired();
2096 // Make sure the request is on a cookie-able url scheme.
2097 for (size_t i
= 0; i
< cookieable_schemes_
.size(); ++i
) {
2098 // We matched a scheme.
2099 if (url
.SchemeIs(cookieable_schemes_
[i
].c_str())) {
2100 // We've matched a supported scheme.
2105 // The scheme didn't match any in our whitelist.
2106 VLOG(kVlogPerCookieMonster
)
2107 << "WARNING: Unsupported cookie scheme: " << url
.scheme();
2111 // Test to see if stats should be recorded, and record them if so.
2112 // The goal here is to get sampling for the average browser-hour of
2113 // activity. We won't take samples when the web isn't being surfed,
2114 // and when the web is being surfed, we'll take samples about every
2115 // kRecordStatisticsIntervalSeconds.
2116 // last_statistic_record_time_ is initialized to Now() rather than null
2117 // in the constructor so that we won't take statistics right after
2118 // startup, to avoid bias from browsers that are started but not used.
2119 void CookieMonster::RecordPeriodicStats(const base::Time
& current_time
) {
2120 const base::TimeDelta
kRecordStatisticsIntervalTime(
2121 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds
));
2123 // If we've taken statistics recently, return.
2124 if (current_time
- last_statistic_record_time_
<=
2125 kRecordStatisticsIntervalTime
) {
2129 // See InitializeHistograms() for details.
2130 histogram_count_
->Add(cookies_
.size());
2132 // More detailed statistics on cookie counts at different granularities.
2133 TimeTicks
beginning_of_time(TimeTicks::Now());
2135 for (CookieMap::const_iterator it_key
= cookies_
.begin();
2136 it_key
!= cookies_
.end();) {
2137 const std::string
& key(it_key
->first
);
2140 typedef std::map
<std::string
, unsigned int> DomainMap
;
2141 DomainMap domain_map
;
2142 CookieMapItPair its_cookies
= cookies_
.equal_range(key
);
2143 while (its_cookies
.first
!= its_cookies
.second
) {
2145 const std::string
& cookie_domain(its_cookies
.first
->second
->Domain());
2146 domain_map
[cookie_domain
]++;
2148 its_cookies
.first
++;
2150 histogram_etldp1_count_
->Add(key_count
);
2151 histogram_domain_per_etldp1_count_
->Add(domain_map
.size());
2152 for (DomainMap::const_iterator domain_map_it
= domain_map
.begin();
2153 domain_map_it
!= domain_map
.end(); domain_map_it
++)
2154 histogram_domain_count_
->Add(domain_map_it
->second
);
2156 it_key
= its_cookies
.second
;
2159 VLOG(kVlogPeriodic
) << "Time for recording cookie stats (us): "
2160 << (TimeTicks::Now() - beginning_of_time
)
2163 last_statistic_record_time_
= current_time
;
2166 // Initialize all histogram counter variables used in this class.
2168 // Normal histogram usage involves using the macros defined in
2169 // histogram.h, which automatically takes care of declaring these
2170 // variables (as statics), initializing them, and accumulating into
2171 // them, all from a single entry point. Unfortunately, that solution
2172 // doesn't work for the CookieMonster, as it's vulnerable to races between
2173 // separate threads executing the same functions and hence initializing the
2174 // same static variables. There isn't a race danger in the histogram
2175 // accumulation calls; they are written to be resilient to simultaneous
2176 // calls from multiple threads.
2178 // The solution taken here is to have per-CookieMonster instance
2179 // variables that are constructed during CookieMonster construction.
2180 // Note that these variables refer to the same underlying histogram,
2181 // so we still race (but safely) with other CookieMonster instances
2182 // for accumulation.
2184 // To do this we've expanded out the individual histogram macros calls,
2185 // with declarations of the variables in the class decl, initialization here
2186 // (done from the class constructor) and direct calls to the accumulation
2187 // methods where needed. The specific histogram macro calls on which the
2188 // initialization is based are included in comments below.
2189 void CookieMonster::InitializeHistograms() {
2190 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2191 histogram_expiration_duration_minutes_
= base::Histogram::FactoryGet(
2192 "Cookie.ExpirationDurationMinutes", 1, kMinutesInTenYears
, 50,
2193 base::Histogram::kUmaTargetedHistogramFlag
);
2194 histogram_between_access_interval_minutes_
= base::Histogram::FactoryGet(
2195 "Cookie.BetweenAccessIntervalMinutes", 1, kMinutesInTenYears
, 50,
2196 base::Histogram::kUmaTargetedHistogramFlag
);
2197 histogram_evicted_last_access_minutes_
= base::Histogram::FactoryGet(
2198 "Cookie.EvictedLastAccessMinutes", 1, kMinutesInTenYears
, 50,
2199 base::Histogram::kUmaTargetedHistogramFlag
);
2200 histogram_count_
= base::Histogram::FactoryGet(
2201 "Cookie.Count", 1, 4000, 50, base::Histogram::kUmaTargetedHistogramFlag
);
2202 histogram_domain_count_
=
2203 base::Histogram::FactoryGet("Cookie.DomainCount", 1, 4000, 50,
2204 base::Histogram::kUmaTargetedHistogramFlag
);
2205 histogram_etldp1_count_
=
2206 base::Histogram::FactoryGet("Cookie.Etldp1Count", 1, 4000, 50,
2207 base::Histogram::kUmaTargetedHistogramFlag
);
2208 histogram_domain_per_etldp1_count_
=
2209 base::Histogram::FactoryGet("Cookie.DomainPerEtldp1Count", 1, 4000, 50,
2210 base::Histogram::kUmaTargetedHistogramFlag
);
2212 // From UMA_HISTOGRAM_COUNTS_10000 & UMA_HISTOGRAM_CUSTOM_COUNTS
2213 histogram_number_duplicate_db_cookies_
=
2214 base::Histogram::FactoryGet("Net.NumDuplicateCookiesInDb", 1, 10000, 50,
2215 base::Histogram::kUmaTargetedHistogramFlag
);
2217 // From UMA_HISTOGRAM_ENUMERATION
2218 histogram_cookie_deletion_cause_
= base::LinearHistogram::FactoryGet(
2219 "Cookie.DeletionCause", 1, DELETE_COOKIE_LAST_ENTRY
- 1,
2220 DELETE_COOKIE_LAST_ENTRY
, base::Histogram::kUmaTargetedHistogramFlag
);
2222 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
2223 histogram_time_blocked_on_load_
= base::Histogram::FactoryTimeGet(
2224 "Cookie.TimeBlockedOnLoad", base::TimeDelta::FromMilliseconds(1),
2225 base::TimeDelta::FromMinutes(1), 50,
2226 base::Histogram::kUmaTargetedHistogramFlag
);
2229 // The system resolution is not high enough, so we can have multiple
2230 // set cookies that result in the same system time. When this happens, we
2231 // increment by one Time unit. Let's hope computers don't get too fast.
2232 Time
CookieMonster::CurrentTime() {
2233 return std::max(Time::Now(), Time::FromInternalValue(
2234 last_time_seen_
.ToInternalValue() + 1));
2237 bool CookieMonster::CopyCookiesForKeyToOtherCookieMonster(
2239 CookieMonster
* other
) {
2240 ScopedVector
<CanonicalCookie
> duplicated_cookies
;
2243 base::AutoLock
autolock(lock_
);
2248 for (CookieMapItPair its
= cookies_
.equal_range(key
);
2249 its
.first
!= its
.second
; ++its
.first
) {
2250 CookieMap::iterator curit
= its
.first
;
2251 CanonicalCookie
* cc
= curit
->second
;
2253 duplicated_cookies
.push_back(cc
->Duplicate());
2258 base::AutoLock
autolock(other
->lock_
);
2259 if (!other
->loaded_
)
2262 // There must not exist any entries for the key to be copied in |other|.
2263 CookieMapItPair its
= other
->cookies_
.equal_range(key
);
2264 if (its
.first
!= its
.second
)
2267 // Store the copied cookies in |other|.
2268 for (ScopedVector
<CanonicalCookie
>::const_iterator it
=
2269 duplicated_cookies
.begin();
2270 it
!= duplicated_cookies
.end(); ++it
) {
2271 other
->InternalInsertCookie(key
, *it
, true);
2274 // Since the cookies are owned by |other| now, weak clear must be used.
2275 duplicated_cookies
.weak_clear();
2281 bool CookieMonster::loaded() {
2282 base::AutoLock
autolock(lock_
);
2286 scoped_ptr
<CookieStore::CookieChangedSubscription
>
2287 CookieMonster::AddCallbackForCookie(const GURL
& gurl
,
2288 const std::string
& name
,
2289 const CookieChangedCallback
& callback
) {
2290 base::AutoLock
autolock(lock_
);
2291 std::pair
<GURL
, std::string
> key(gurl
, name
);
2292 if (hook_map_
.count(key
) == 0)
2293 hook_map_
[key
] = make_linked_ptr(new CookieChangedCallbackList());
2294 return hook_map_
[key
]->Add(
2295 base::Bind(&RunAsync
, base::MessageLoopProxy::current(), callback
));
2298 void CookieMonster::RunCallbacks(const CanonicalCookie
& cookie
, bool removed
) {
2299 lock_
.AssertAcquired();
2301 opts
.set_include_httponly();
2302 opts
.set_include_first_party_only();
2303 // Note that the callbacks in hook_map_ are wrapped with MakeAsync(), so they
2304 // are guaranteed to not take long - they just post a RunAsync task back to
2305 // the appropriate thread's message loop and return. It is important that this
2306 // method not run user-supplied callbacks directly, since the CookieMonster
2307 // lock is held and it is easy to accidentally introduce deadlocks.
2308 for (CookieChangedHookMap::iterator it
= hook_map_
.begin();
2309 it
!= hook_map_
.end(); ++it
) {
2310 std::pair
<GURL
, std::string
> key
= it
->first
;
2311 if (cookie
.IncludeForRequestURL(key
.first
, opts
) &&
2312 cookie
.Name() == key
.second
) {
2313 it
->second
->Notify(cookie
, removed
);