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/message_loop/message_loop.h"
57 #include "base/message_loop/message_loop_proxy.h"
58 #include "base/metrics/histogram.h"
59 #include "base/strings/string_util.h"
60 #include "base/strings/stringprintf.h"
61 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
62 #include "net/cookies/canonical_cookie.h"
63 #include "net/cookies/cookie_util.h"
64 #include "net/cookies/parsed_cookie.h"
68 using base::TimeDelta
;
69 using base::TimeTicks
;
71 // In steady state, most cookie requests can be satisfied by the in memory
72 // cookie monster store. However, if a request comes in during the initial
73 // cookie load, it must be delayed until that load completes. That is done by
74 // queueing it on CookieMonster::tasks_pending_ and running it when notification
75 // of cookie load completion is received via CookieMonster::OnLoaded. This
76 // callback is passed to the persistent store from CookieMonster::InitStore(),
77 // which is called on the first operation invoked on the CookieMonster.
79 // On the browser critical paths (e.g. for loading initial web pages in a
80 // session restore) it may take too long to wait for the full load. If a cookie
81 // request is for a specific URL, DoCookieTaskForURL is called, which triggers a
82 // priority load if the key is not loaded yet by calling PersistentCookieStore
83 // :: LoadCookiesForKey. The request is queued in
84 // CookieMonster::tasks_pending_for_key_ and executed upon receiving
85 // notification of key load completion via CookieMonster::OnKeyLoaded(). If
86 // multiple requests for the same eTLD+1 are received before key load
87 // completion, only the first request calls
88 // PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
89 // in CookieMonster::tasks_pending_for_key_ and executed upon receiving
90 // notification of key load completion triggered by the first request for the
93 static const int kMinutesInTenYears
= 10 * 365 * 24 * 60;
97 // See comments at declaration of these variables in cookie_monster.h
99 const size_t CookieMonster::kDomainMaxCookies
= 180;
100 const size_t CookieMonster::kDomainPurgeCookies
= 30;
101 const size_t CookieMonster::kMaxCookies
= 3300;
102 const size_t CookieMonster::kPurgeCookies
= 300;
104 const size_t CookieMonster::kDomainCookiesQuotaLow
= 30;
105 const size_t CookieMonster::kDomainCookiesQuotaMedium
= 50;
106 const size_t CookieMonster::kDomainCookiesQuotaHigh
=
107 kDomainMaxCookies
- kDomainPurgeCookies
108 - kDomainCookiesQuotaLow
- kDomainCookiesQuotaMedium
;
110 const int CookieMonster::kSafeFromGlobalPurgeDays
= 30;
114 bool ContainsControlCharacter(const std::string
& s
) {
115 for (std::string::const_iterator i
= s
.begin(); i
!= s
.end(); ++i
) {
116 if ((*i
>= 0) && (*i
<= 31))
123 typedef std::vector
<CanonicalCookie
*> CanonicalCookieVector
;
125 // Default minimum delay after updating a cookie's LastAccessDate before we
126 // will update it again.
127 const int kDefaultAccessUpdateThresholdSeconds
= 60;
129 // Comparator to sort cookies from highest creation date to lowest
131 struct OrderByCreationTimeDesc
{
132 bool operator()(const CookieMonster::CookieMap::iterator
& a
,
133 const CookieMonster::CookieMap::iterator
& b
) const {
134 return a
->second
->CreationDate() > b
->second
->CreationDate();
138 // Constants for use in VLOG
139 const int kVlogPerCookieMonster
= 1;
140 const int kVlogPeriodic
= 3;
141 const int kVlogGarbageCollection
= 5;
142 const int kVlogSetCookies
= 7;
143 const int kVlogGetCookies
= 9;
145 // Mozilla sorts on the path length (longest first), and then it
146 // sorts by creation time (oldest first).
147 // The RFC says the sort order for the domain attribute is undefined.
148 bool CookieSorter(CanonicalCookie
* cc1
, CanonicalCookie
* cc2
) {
149 if (cc1
->Path().length() == cc2
->Path().length())
150 return cc1
->CreationDate() < cc2
->CreationDate();
151 return cc1
->Path().length() > cc2
->Path().length();
154 bool LRACookieSorter(const CookieMonster::CookieMap::iterator
& it1
,
155 const CookieMonster::CookieMap::iterator
& it2
) {
156 // Cookies accessed less recently should be deleted first.
157 if (it1
->second
->LastAccessDate() != it2
->second
->LastAccessDate())
158 return it1
->second
->LastAccessDate() < it2
->second
->LastAccessDate();
160 // In rare cases we might have two cookies with identical last access times.
161 // To preserve the stability of the sort, in these cases prefer to delete
162 // older cookies over newer ones. CreationDate() is guaranteed to be unique.
163 return it1
->second
->CreationDate() < it2
->second
->CreationDate();
166 // Our strategy to find duplicates is:
167 // (1) Build a map from (cookiename, cookiepath) to
168 // {list of cookies with this signature, sorted by creation time}.
169 // (2) For each list with more than 1 entry, keep the cookie having the
170 // most recent creation time, and delete the others.
172 // Two cookies are considered equivalent if they have the same domain,
174 struct CookieSignature
{
176 CookieSignature(const std::string
& name
,
177 const std::string
& domain
,
178 const std::string
& path
)
179 : 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(
209 CookieMonster::CookieItVector::iterator it_begin
,
210 CookieMonster::CookieItVector::iterator it_end
,
212 DCHECK_LT(static_cast<int>(num_sort
), it_end
- it_begin
);
213 std::partial_sort(it_begin
, it_begin
+ num_sort
+ 1, it_end
, LRACookieSorter
);
216 // Predicate to support PartitionCookieByPriority().
217 struct CookiePriorityEqualsTo
218 : std::unary_function
<const CookieMonster::CookieMap::iterator
, bool> {
219 CookiePriorityEqualsTo(CookiePriority priority
)
220 : priority_(priority
) {}
222 bool operator()(const CookieMonster::CookieMap::iterator it
) const {
223 return it
->second
->Priority() == priority_
;
226 const CookiePriority priority_
;
229 // For a CookieItVector iterator range [|it_begin|, |it_end|),
230 // moves all cookies with a given |priority| to the beginning of the list.
231 // Returns: An iterator in [it_begin, it_end) to the first element with
232 // priority != |priority|, or |it_end| if all have priority == |priority|.
233 CookieMonster::CookieItVector::iterator
PartitionCookieByPriority(
234 CookieMonster::CookieItVector::iterator it_begin
,
235 CookieMonster::CookieItVector::iterator it_end
,
236 CookiePriority priority
) {
237 return std::partition(it_begin
, it_end
, CookiePriorityEqualsTo(priority
));
240 bool LowerBoundAccessDateComparator(
241 const CookieMonster::CookieMap::iterator it
, const Time
& access_date
) {
242 return it
->second
->LastAccessDate() < access_date
;
245 // For a CookieItVector iterator range [|it_begin|, |it_end|)
246 // from a CookieItVector sorted by LastAccessDate(), returns the
247 // first iterator with access date >= |access_date|, or cookie_its_end if this
249 CookieMonster::CookieItVector::iterator
LowerBoundAccessDate(
250 const CookieMonster::CookieItVector::iterator its_begin
,
251 const CookieMonster::CookieItVector::iterator its_end
,
252 const Time
& access_date
) {
253 return std::lower_bound(its_begin
, its_end
, access_date
,
254 LowerBoundAccessDateComparator
);
257 // Mapping between DeletionCause and CookieMonsterDelegate::ChangeCause; the
258 // mapping also provides a boolean that specifies whether or not an
259 // OnCookieChanged notification ought to be generated.
260 typedef struct ChangeCausePair_struct
{
261 CookieMonsterDelegate::ChangeCause cause
;
264 ChangeCausePair ChangeCauseMapping
[] = {
265 // DELETE_COOKIE_EXPLICIT
266 { CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, true },
267 // DELETE_COOKIE_OVERWRITE
268 { CookieMonsterDelegate::CHANGE_COOKIE_OVERWRITE
, true },
269 // DELETE_COOKIE_EXPIRED
270 { CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED
, true },
271 // DELETE_COOKIE_EVICTED
272 { CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true },
273 // DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
274 { CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, false },
275 // DELETE_COOKIE_DONT_RECORD
276 { CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, false },
277 // DELETE_COOKIE_EVICTED_DOMAIN
278 { CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true },
279 // DELETE_COOKIE_EVICTED_GLOBAL
280 { CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true },
281 // DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
282 { CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true },
283 // DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
284 { CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true },
285 // DELETE_COOKIE_EXPIRED_OVERWRITE
286 { CookieMonsterDelegate::CHANGE_COOKIE_EXPIRED_OVERWRITE
, true },
287 // DELETE_COOKIE_CONTROL_CHAR
288 { CookieMonsterDelegate::CHANGE_COOKIE_EVICTED
, true},
289 // DELETE_COOKIE_LAST_ENTRY
290 { CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
, false }
293 std::string
BuildCookieLine(const CanonicalCookieVector
& cookies
) {
294 std::string cookie_line
;
295 for (CanonicalCookieVector::const_iterator it
= cookies
.begin();
296 it
!= cookies
.end(); ++it
) {
297 if (it
!= cookies
.begin())
299 // In Mozilla if you set a cookie like AAAA, it will have an empty token
300 // and a value of AAAA. When it sends the cookie back, it will send AAAA,
301 // so we need to avoid sending =AAAA for a blank token value.
302 if (!(*it
)->Name().empty())
303 cookie_line
+= (*it
)->Name() + "=";
304 cookie_line
+= (*it
)->Value();
311 CookieMonster::CookieMonster(PersistentCookieStore
* store
,
312 CookieMonsterDelegate
* delegate
)
313 : initialized_(false),
316 last_access_threshold_(
317 TimeDelta::FromSeconds(kDefaultAccessUpdateThresholdSeconds
)),
319 last_statistic_record_time_(Time::Now()),
320 keep_expired_cookies_(false),
321 persist_session_cookies_(false) {
322 InitializeHistograms();
323 SetDefaultCookieableSchemes();
326 CookieMonster::CookieMonster(PersistentCookieStore
* store
,
327 CookieMonsterDelegate
* delegate
,
328 int last_access_threshold_milliseconds
)
329 : initialized_(false),
332 last_access_threshold_(base::TimeDelta::FromMilliseconds(
333 last_access_threshold_milliseconds
)),
335 last_statistic_record_time_(base::Time::Now()),
336 keep_expired_cookies_(false),
337 persist_session_cookies_(false) {
338 InitializeHistograms();
339 SetDefaultCookieableSchemes();
343 // Task classes for queueing the coming request.
345 class CookieMonster::CookieMonsterTask
346 : public base::RefCountedThreadSafe
<CookieMonsterTask
> {
348 // Runs the task and invokes the client callback on the thread that
349 // originally constructed the task.
350 virtual void Run() = 0;
353 explicit CookieMonsterTask(CookieMonster
* cookie_monster
);
354 virtual ~CookieMonsterTask();
356 // Invokes the callback immediately, if the current thread is the one
357 // that originated the task, or queues the callback for execution on the
358 // appropriate thread. Maintains a reference to this CookieMonsterTask
359 // instance until the callback completes.
360 void InvokeCallback(base::Closure callback
);
362 CookieMonster
* cookie_monster() {
363 return cookie_monster_
;
367 friend class base::RefCountedThreadSafe
<CookieMonsterTask
>;
369 CookieMonster
* cookie_monster_
;
370 scoped_refptr
<base::MessageLoopProxy
> thread_
;
372 DISALLOW_COPY_AND_ASSIGN(CookieMonsterTask
);
375 CookieMonster::CookieMonsterTask::CookieMonsterTask(
376 CookieMonster
* cookie_monster
)
377 : cookie_monster_(cookie_monster
),
378 thread_(base::MessageLoopProxy::current()) {
381 CookieMonster::CookieMonsterTask::~CookieMonsterTask() {}
383 // Unfortunately, one cannot re-bind a Callback with parameters into a closure.
384 // Therefore, the closure passed to InvokeCallback is a clumsy binding of
385 // Callback::Run on a wrapped Callback instance. Since Callback is not
386 // reference counted, we bind to an instance that is a member of the
387 // CookieMonsterTask subclass. Then, we cannot simply post the callback to a
388 // message loop because the underlying instance may be destroyed (along with the
389 // CookieMonsterTask instance) in the interim. Therefore, we post a callback
390 // bound to the CookieMonsterTask, which *is* reference counted (thus preventing
391 // destruction of the original callback), and which invokes the closure (which
392 // invokes the original callback with the returned data).
393 void CookieMonster::CookieMonsterTask::InvokeCallback(base::Closure callback
) {
394 if (thread_
->BelongsToCurrentThread()) {
397 thread_
->PostTask(FROM_HERE
, base::Bind(
398 &CookieMonsterTask::InvokeCallback
, this, callback
));
402 // Task class for SetCookieWithDetails call.
403 class CookieMonster::SetCookieWithDetailsTask
: public CookieMonsterTask
{
405 SetCookieWithDetailsTask(CookieMonster
* cookie_monster
,
407 const std::string
& name
,
408 const std::string
& value
,
409 const std::string
& domain
,
410 const std::string
& path
,
411 const base::Time
& expiration_time
,
414 CookiePriority priority
,
415 const SetCookiesCallback
& callback
)
416 : CookieMonsterTask(cookie_monster
),
422 expiration_time_(expiration_time
),
424 http_only_(http_only
),
426 callback_(callback
) {
429 // CookieMonsterTask:
430 virtual void Run() OVERRIDE
;
433 virtual ~SetCookieWithDetailsTask() {}
441 base::Time expiration_time_
;
444 CookiePriority priority_
;
445 SetCookiesCallback callback_
;
447 DISALLOW_COPY_AND_ASSIGN(SetCookieWithDetailsTask
);
450 void CookieMonster::SetCookieWithDetailsTask::Run() {
451 bool success
= this->cookie_monster()->
452 SetCookieWithDetails(url_
, name_
, value_
, domain_
, path_
,
453 expiration_time_
, secure_
, http_only_
, priority_
);
454 if (!callback_
.is_null()) {
455 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run
,
456 base::Unretained(&callback_
), success
));
460 // Task class for GetAllCookies call.
461 class CookieMonster::GetAllCookiesTask
: public CookieMonsterTask
{
463 GetAllCookiesTask(CookieMonster
* cookie_monster
,
464 const GetCookieListCallback
& callback
)
465 : CookieMonsterTask(cookie_monster
),
466 callback_(callback
) {
470 virtual void Run() OVERRIDE
;
473 virtual ~GetAllCookiesTask() {}
476 GetCookieListCallback callback_
;
478 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesTask
);
481 void CookieMonster::GetAllCookiesTask::Run() {
482 if (!callback_
.is_null()) {
483 CookieList cookies
= this->cookie_monster()->GetAllCookies();
484 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run
,
485 base::Unretained(&callback_
), cookies
));
489 // Task class for GetAllCookiesForURLWithOptions call.
490 class CookieMonster::GetAllCookiesForURLWithOptionsTask
491 : public CookieMonsterTask
{
493 GetAllCookiesForURLWithOptionsTask(
494 CookieMonster
* cookie_monster
,
496 const CookieOptions
& options
,
497 const GetCookieListCallback
& callback
)
498 : CookieMonsterTask(cookie_monster
),
501 callback_(callback
) {
504 // CookieMonsterTask:
505 virtual void Run() OVERRIDE
;
508 virtual ~GetAllCookiesForURLWithOptionsTask() {}
512 CookieOptions options_
;
513 GetCookieListCallback callback_
;
515 DISALLOW_COPY_AND_ASSIGN(GetAllCookiesForURLWithOptionsTask
);
518 void CookieMonster::GetAllCookiesForURLWithOptionsTask::Run() {
519 if (!callback_
.is_null()) {
520 CookieList cookies
= this->cookie_monster()->
521 GetAllCookiesForURLWithOptions(url_
, options_
);
522 this->InvokeCallback(base::Bind(&GetCookieListCallback::Run
,
523 base::Unretained(&callback_
), cookies
));
527 template <typename Result
> struct CallbackType
{
528 typedef base::Callback
<void(Result
)> Type
;
531 template <> struct CallbackType
<void> {
532 typedef base::Closure Type
;
535 // Base task class for Delete*Task.
536 template <typename Result
>
537 class CookieMonster::DeleteTask
: public CookieMonsterTask
{
539 DeleteTask(CookieMonster
* cookie_monster
,
540 const typename CallbackType
<Result
>::Type
& callback
)
541 : CookieMonsterTask(cookie_monster
),
542 callback_(callback
) {
545 // CookieMonsterTask:
546 virtual void Run() OVERRIDE
;
549 // Runs the delete task and returns a result.
550 virtual Result
RunDeleteTask() = 0;
551 base::Closure
RunDeleteTaskAndBindCallback();
552 void FlushDone(const base::Closure
& callback
);
554 typename CallbackType
<Result
>::Type callback_
;
556 DISALLOW_COPY_AND_ASSIGN(DeleteTask
);
559 template <typename Result
>
560 base::Closure
CookieMonster::DeleteTask
<Result
>::
561 RunDeleteTaskAndBindCallback() {
562 Result result
= RunDeleteTask();
563 if (callback_
.is_null())
564 return base::Closure();
565 return base::Bind(callback_
, result
);
569 base::Closure
CookieMonster::DeleteTask
<void>::RunDeleteTaskAndBindCallback() {
574 template <typename Result
>
575 void CookieMonster::DeleteTask
<Result
>::Run() {
576 this->cookie_monster()->FlushStore(
577 base::Bind(&DeleteTask
<Result
>::FlushDone
, this,
578 RunDeleteTaskAndBindCallback()));
581 template <typename Result
>
582 void CookieMonster::DeleteTask
<Result
>::FlushDone(
583 const base::Closure
& callback
) {
584 if (!callback
.is_null()) {
585 this->InvokeCallback(callback
);
589 // Task class for DeleteAll call.
590 class CookieMonster::DeleteAllTask
: public DeleteTask
<int> {
592 DeleteAllTask(CookieMonster
* cookie_monster
,
593 const DeleteCallback
& callback
)
594 : DeleteTask
<int>(cookie_monster
, callback
) {
598 virtual int RunDeleteTask() OVERRIDE
;
601 virtual ~DeleteAllTask() {}
604 DISALLOW_COPY_AND_ASSIGN(DeleteAllTask
);
607 int CookieMonster::DeleteAllTask::RunDeleteTask() {
608 return this->cookie_monster()->DeleteAll(true);
611 // Task class for DeleteAllCreatedBetween call.
612 class CookieMonster::DeleteAllCreatedBetweenTask
: public DeleteTask
<int> {
614 DeleteAllCreatedBetweenTask(CookieMonster
* cookie_monster
,
615 const Time
& delete_begin
,
616 const Time
& delete_end
,
617 const DeleteCallback
& callback
)
618 : DeleteTask
<int>(cookie_monster
, callback
),
619 delete_begin_(delete_begin
),
620 delete_end_(delete_end
) {
624 virtual int RunDeleteTask() OVERRIDE
;
627 virtual ~DeleteAllCreatedBetweenTask() {}
633 DISALLOW_COPY_AND_ASSIGN(DeleteAllCreatedBetweenTask
);
636 int CookieMonster::DeleteAllCreatedBetweenTask::RunDeleteTask() {
637 return this->cookie_monster()->
638 DeleteAllCreatedBetween(delete_begin_
, delete_end_
);
641 // Task class for DeleteAllForHost call.
642 class CookieMonster::DeleteAllForHostTask
: public DeleteTask
<int> {
644 DeleteAllForHostTask(CookieMonster
* cookie_monster
,
646 const DeleteCallback
& callback
)
647 : DeleteTask
<int>(cookie_monster
, callback
),
652 virtual int RunDeleteTask() OVERRIDE
;
655 virtual ~DeleteAllForHostTask() {}
660 DISALLOW_COPY_AND_ASSIGN(DeleteAllForHostTask
);
663 int CookieMonster::DeleteAllForHostTask::RunDeleteTask() {
664 return this->cookie_monster()->DeleteAllForHost(url_
);
667 // Task class for DeleteAllCreatedBetweenForHost call.
668 class CookieMonster::DeleteAllCreatedBetweenForHostTask
669 : public DeleteTask
<int> {
671 DeleteAllCreatedBetweenForHostTask(
672 CookieMonster
* cookie_monster
,
676 const DeleteCallback
& callback
)
677 : DeleteTask
<int>(cookie_monster
, callback
),
678 delete_begin_(delete_begin
),
679 delete_end_(delete_end
),
684 virtual int RunDeleteTask() OVERRIDE
;
687 virtual ~DeleteAllCreatedBetweenForHostTask() {}
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
),
713 virtual bool RunDeleteTask() OVERRIDE
;
716 virtual ~DeleteCanonicalCookieTask() {}
719 CanonicalCookie cookie_
;
721 DISALLOW_COPY_AND_ASSIGN(DeleteCanonicalCookieTask
);
724 bool CookieMonster::DeleteCanonicalCookieTask::RunDeleteTask() {
725 return this->cookie_monster()->DeleteCanonicalCookie(cookie_
);
728 // Task class for SetCookieWithOptions call.
729 class CookieMonster::SetCookieWithOptionsTask
: public CookieMonsterTask
{
731 SetCookieWithOptionsTask(CookieMonster
* cookie_monster
,
733 const std::string
& cookie_line
,
734 const CookieOptions
& options
,
735 const SetCookiesCallback
& callback
)
736 : CookieMonsterTask(cookie_monster
),
738 cookie_line_(cookie_line
),
740 callback_(callback
) {
743 // CookieMonsterTask:
744 virtual void Run() OVERRIDE
;
747 virtual ~SetCookieWithOptionsTask() {}
751 std::string cookie_line_
;
752 CookieOptions options_
;
753 SetCookiesCallback callback_
;
755 DISALLOW_COPY_AND_ASSIGN(SetCookieWithOptionsTask
);
758 void CookieMonster::SetCookieWithOptionsTask::Run() {
759 bool result
= this->cookie_monster()->
760 SetCookieWithOptions(url_
, cookie_line_
, options_
);
761 if (!callback_
.is_null()) {
762 this->InvokeCallback(base::Bind(&SetCookiesCallback::Run
,
763 base::Unretained(&callback_
), result
));
767 // Task class for GetCookiesWithOptions call.
768 class CookieMonster::GetCookiesWithOptionsTask
: public CookieMonsterTask
{
770 GetCookiesWithOptionsTask(CookieMonster
* cookie_monster
,
772 const CookieOptions
& options
,
773 const GetCookiesCallback
& callback
)
774 : CookieMonsterTask(cookie_monster
),
777 callback_(callback
) {
780 // CookieMonsterTask:
781 virtual void Run() OVERRIDE
;
784 virtual ~GetCookiesWithOptionsTask() {}
788 CookieOptions options_
;
789 GetCookiesCallback callback_
;
791 DISALLOW_COPY_AND_ASSIGN(GetCookiesWithOptionsTask
);
794 void CookieMonster::GetCookiesWithOptionsTask::Run() {
795 std::string cookie
= this->cookie_monster()->
796 GetCookiesWithOptions(url_
, options_
);
797 if (!callback_
.is_null()) {
798 this->InvokeCallback(base::Bind(&GetCookiesCallback::Run
,
799 base::Unretained(&callback_
), cookie
));
803 // Task class for DeleteCookie call.
804 class CookieMonster::DeleteCookieTask
: public DeleteTask
<void> {
806 DeleteCookieTask(CookieMonster
* cookie_monster
,
808 const std::string
& cookie_name
,
809 const base::Closure
& callback
)
810 : DeleteTask
<void>(cookie_monster
, callback
),
812 cookie_name_(cookie_name
) {
816 virtual void RunDeleteTask() OVERRIDE
;
819 virtual ~DeleteCookieTask() {}
823 std::string cookie_name_
;
825 DISALLOW_COPY_AND_ASSIGN(DeleteCookieTask
);
828 void CookieMonster::DeleteCookieTask::RunDeleteTask() {
829 this->cookie_monster()->DeleteCookie(url_
, cookie_name_
);
832 // Task class for DeleteSessionCookies call.
833 class CookieMonster::DeleteSessionCookiesTask
: public DeleteTask
<int> {
835 DeleteSessionCookiesTask(CookieMonster
* cookie_monster
,
836 const DeleteCallback
& callback
)
837 : DeleteTask
<int>(cookie_monster
, callback
) {
841 virtual int RunDeleteTask() OVERRIDE
;
844 virtual ~DeleteSessionCookiesTask() {}
848 DISALLOW_COPY_AND_ASSIGN(DeleteSessionCookiesTask
);
851 int CookieMonster::DeleteSessionCookiesTask::RunDeleteTask() {
852 return this->cookie_monster()->DeleteSessionCookies();
855 // Task class for HasCookiesForETLDP1Task call.
856 class CookieMonster::HasCookiesForETLDP1Task
: public CookieMonsterTask
{
858 HasCookiesForETLDP1Task(
859 CookieMonster
* cookie_monster
,
860 const std::string
& etldp1
,
861 const HasCookiesForETLDP1Callback
& callback
)
862 : CookieMonsterTask(cookie_monster
),
864 callback_(callback
) {
867 // CookieMonsterTask:
868 virtual void Run() OVERRIDE
;
871 virtual ~HasCookiesForETLDP1Task() {}
875 HasCookiesForETLDP1Callback callback_
;
877 DISALLOW_COPY_AND_ASSIGN(HasCookiesForETLDP1Task
);
880 void CookieMonster::HasCookiesForETLDP1Task::Run() {
881 bool result
= this->cookie_monster()->HasCookiesForETLDP1(etldp1_
);
882 if (!callback_
.is_null()) {
883 this->InvokeCallback(
884 base::Bind(&HasCookiesForETLDP1Callback::Run
,
885 base::Unretained(&callback_
), result
));
889 // Asynchronous CookieMonster API
891 void CookieMonster::SetCookieWithDetailsAsync(
893 const std::string
& name
,
894 const std::string
& value
,
895 const std::string
& domain
,
896 const std::string
& path
,
897 const Time
& expiration_time
,
900 CookiePriority priority
,
901 const SetCookiesCallback
& callback
) {
902 scoped_refptr
<SetCookieWithDetailsTask
> task
=
903 new SetCookieWithDetailsTask(this, url
, name
, value
, domain
, path
,
904 expiration_time
, secure
, http_only
, priority
,
907 DoCookieTaskForURL(task
, url
);
910 void CookieMonster::GetAllCookiesAsync(const GetCookieListCallback
& callback
) {
911 scoped_refptr
<GetAllCookiesTask
> task
=
912 new GetAllCookiesTask(this, callback
);
918 void CookieMonster::GetAllCookiesForURLWithOptionsAsync(
920 const CookieOptions
& options
,
921 const GetCookieListCallback
& callback
) {
922 scoped_refptr
<GetAllCookiesForURLWithOptionsTask
> task
=
923 new GetAllCookiesForURLWithOptionsTask(this, url
, options
, callback
);
925 DoCookieTaskForURL(task
, url
);
928 void CookieMonster::GetAllCookiesForURLAsync(
929 const GURL
& url
, const GetCookieListCallback
& callback
) {
930 CookieOptions options
;
931 options
.set_include_httponly();
932 scoped_refptr
<GetAllCookiesForURLWithOptionsTask
> task
=
933 new GetAllCookiesForURLWithOptionsTask(this, url
, options
, callback
);
935 DoCookieTaskForURL(task
, url
);
938 void CookieMonster::HasCookiesForETLDP1Async(
939 const std::string
& etldp1
,
940 const HasCookiesForETLDP1Callback
& callback
) {
941 scoped_refptr
<HasCookiesForETLDP1Task
> task
=
942 new HasCookiesForETLDP1Task(this, etldp1
, callback
);
944 DoCookieTaskForURL(task
, GURL("http://" + etldp1
));
947 void CookieMonster::DeleteAllAsync(const DeleteCallback
& callback
) {
948 scoped_refptr
<DeleteAllTask
> task
=
949 new DeleteAllTask(this, callback
);
954 void CookieMonster::DeleteAllCreatedBetweenAsync(
955 const Time
& delete_begin
, const Time
& delete_end
,
956 const DeleteCallback
& callback
) {
957 scoped_refptr
<DeleteAllCreatedBetweenTask
> task
=
958 new DeleteAllCreatedBetweenTask(this, delete_begin
, delete_end
,
964 void CookieMonster::DeleteAllCreatedBetweenForHostAsync(
965 const Time delete_begin
,
966 const Time delete_end
,
968 const DeleteCallback
& callback
) {
969 scoped_refptr
<DeleteAllCreatedBetweenForHostTask
> task
=
970 new DeleteAllCreatedBetweenForHostTask(
971 this, delete_begin
, delete_end
, url
, callback
);
973 DoCookieTaskForURL(task
, url
);
976 void CookieMonster::DeleteAllForHostAsync(
977 const GURL
& url
, const DeleteCallback
& callback
) {
978 scoped_refptr
<DeleteAllForHostTask
> task
=
979 new DeleteAllForHostTask(this, url
, callback
);
981 DoCookieTaskForURL(task
, url
);
984 void CookieMonster::DeleteCanonicalCookieAsync(
985 const CanonicalCookie
& cookie
,
986 const DeleteCookieCallback
& callback
) {
987 scoped_refptr
<DeleteCanonicalCookieTask
> task
=
988 new DeleteCanonicalCookieTask(this, cookie
, callback
);
993 void CookieMonster::SetCookieWithOptionsAsync(
995 const std::string
& cookie_line
,
996 const CookieOptions
& options
,
997 const SetCookiesCallback
& callback
) {
998 scoped_refptr
<SetCookieWithOptionsTask
> task
=
999 new SetCookieWithOptionsTask(this, url
, cookie_line
, options
, callback
);
1001 DoCookieTaskForURL(task
, url
);
1004 void CookieMonster::GetCookiesWithOptionsAsync(
1006 const CookieOptions
& options
,
1007 const GetCookiesCallback
& callback
) {
1008 scoped_refptr
<GetCookiesWithOptionsTask
> task
=
1009 new GetCookiesWithOptionsTask(this, url
, options
, callback
);
1011 DoCookieTaskForURL(task
, url
);
1014 void CookieMonster::DeleteCookieAsync(const GURL
& url
,
1015 const std::string
& cookie_name
,
1016 const base::Closure
& callback
) {
1017 scoped_refptr
<DeleteCookieTask
> task
=
1018 new DeleteCookieTask(this, url
, cookie_name
, callback
);
1020 DoCookieTaskForURL(task
, url
);
1023 void CookieMonster::DeleteSessionCookiesAsync(
1024 const CookieStore::DeleteCallback
& callback
) {
1025 scoped_refptr
<DeleteSessionCookiesTask
> task
=
1026 new DeleteSessionCookiesTask(this, callback
);
1031 void CookieMonster::DoCookieTask(
1032 const scoped_refptr
<CookieMonsterTask
>& task_item
) {
1034 base::AutoLock
autolock(lock_
);
1037 tasks_pending_
.push(task_item
);
1045 void CookieMonster::DoCookieTaskForURL(
1046 const scoped_refptr
<CookieMonsterTask
>& task_item
,
1049 base::AutoLock
autolock(lock_
);
1051 // If cookies for the requested domain key (eTLD+1) have been loaded from DB
1052 // then run the task, otherwise load from DB.
1054 // Checks if the domain key has been loaded.
1055 std::string
key(cookie_util::GetEffectiveDomain(url
.scheme(),
1057 if (keys_loaded_
.find(key
) == keys_loaded_
.end()) {
1058 std::map
<std::string
, std::deque
<scoped_refptr
<CookieMonsterTask
> > >
1059 ::iterator it
= tasks_pending_for_key_
.find(key
);
1060 if (it
== tasks_pending_for_key_
.end()) {
1061 store_
->LoadCookiesForKey(key
,
1062 base::Bind(&CookieMonster::OnKeyLoaded
, this, key
));
1063 it
= tasks_pending_for_key_
.insert(std::make_pair(key
,
1064 std::deque
<scoped_refptr
<CookieMonsterTask
> >())).first
;
1066 it
->second
.push_back(task_item
);
1074 bool CookieMonster::SetCookieWithDetails(const GURL
& url
,
1075 const std::string
& name
,
1076 const std::string
& value
,
1077 const std::string
& domain
,
1078 const std::string
& path
,
1079 const base::Time
& expiration_time
,
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
,
1094 secure
, http_only
, priority
));
1099 CookieOptions options
;
1100 options
.set_include_httponly();
1101 return SetCanonicalCookie(&cc
, creation_time
, options
);
1104 bool CookieMonster::InitializeFrom(const CookieList
& list
) {
1105 base::AutoLock
autolock(lock_
);
1107 for (net::CookieList::const_iterator iter
= list
.begin();
1108 iter
!= list
.end(); ++iter
) {
1109 scoped_ptr
<CanonicalCookie
> cookie(new CanonicalCookie(*iter
));
1110 net::CookieOptions options
;
1111 options
.set_include_httponly();
1112 if (!SetCanonicalCookie(&cookie
, cookie
->CreationDate(), options
))
1118 CookieList
CookieMonster::GetAllCookies() {
1119 base::AutoLock
autolock(lock_
);
1121 // This function is being called to scrape the cookie list for management UI
1122 // or similar. We shouldn't show expired cookies in this list since it will
1123 // just be confusing to users, and this function is called rarely enough (and
1124 // is already slow enough) that it's OK to take the time to garbage collect
1125 // the expired cookies now.
1127 // Note that this does not prune cookies to be below our limits (if we've
1128 // exceeded them) the way that calling GarbageCollect() would.
1129 GarbageCollectExpired(Time::Now(),
1130 CookieMapItPair(cookies_
.begin(), cookies_
.end()),
1133 // Copy the CanonicalCookie pointers from the map so that we can use the same
1134 // sorter as elsewhere, then copy the result out.
1135 std::vector
<CanonicalCookie
*> cookie_ptrs
;
1136 cookie_ptrs
.reserve(cookies_
.size());
1137 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end(); ++it
)
1138 cookie_ptrs
.push_back(it
->second
);
1139 std::sort(cookie_ptrs
.begin(), cookie_ptrs
.end(), CookieSorter
);
1141 CookieList cookie_list
;
1142 cookie_list
.reserve(cookie_ptrs
.size());
1143 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookie_ptrs
.begin();
1144 it
!= cookie_ptrs
.end(); ++it
)
1145 cookie_list
.push_back(**it
);
1150 CookieList
CookieMonster::GetAllCookiesForURLWithOptions(
1152 const CookieOptions
& options
) {
1153 base::AutoLock
autolock(lock_
);
1155 std::vector
<CanonicalCookie
*> cookie_ptrs
;
1156 FindCookiesForHostAndDomain(url
, options
, false, &cookie_ptrs
);
1157 std::sort(cookie_ptrs
.begin(), cookie_ptrs
.end(), CookieSorter
);
1160 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookie_ptrs
.begin();
1161 it
!= cookie_ptrs
.end(); it
++)
1162 cookies
.push_back(**it
);
1167 CookieList
CookieMonster::GetAllCookiesForURL(const GURL
& url
) {
1168 CookieOptions options
;
1169 options
.set_include_httponly();
1171 return GetAllCookiesForURLWithOptions(url
, options
);
1174 int CookieMonster::DeleteAll(bool sync_to_store
) {
1175 base::AutoLock
autolock(lock_
);
1177 int num_deleted
= 0;
1178 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1179 CookieMap::iterator curit
= it
;
1181 InternalDeleteCookie(curit
, sync_to_store
,
1182 sync_to_store
? DELETE_COOKIE_EXPLICIT
:
1183 DELETE_COOKIE_DONT_RECORD
/* Destruction. */);
1190 int CookieMonster::DeleteAllCreatedBetween(const Time
& delete_begin
,
1191 const Time
& delete_end
) {
1192 base::AutoLock
autolock(lock_
);
1194 int num_deleted
= 0;
1195 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1196 CookieMap::iterator curit
= it
;
1197 CanonicalCookie
* cc
= curit
->second
;
1200 if (cc
->CreationDate() >= delete_begin
&&
1201 (delete_end
.is_null() || cc
->CreationDate() < delete_end
)) {
1202 InternalDeleteCookie(curit
,
1203 true, /*sync_to_store*/
1204 DELETE_COOKIE_EXPLICIT
);
1212 int CookieMonster::DeleteAllCreatedBetweenForHost(const Time delete_begin
,
1213 const Time delete_end
,
1215 base::AutoLock
autolock(lock_
);
1217 if (!HasCookieableScheme(url
))
1220 const std::string
host(url
.host());
1222 // We store host cookies in the store by their canonical host name;
1223 // domain cookies are stored with a leading ".". So this is a pretty
1224 // simple lookup and per-cookie delete.
1225 int num_deleted
= 0;
1226 for (CookieMapItPair its
= cookies_
.equal_range(GetKey(host
));
1227 its
.first
!= its
.second
;) {
1228 CookieMap::iterator curit
= its
.first
;
1231 const CanonicalCookie
* const cc
= curit
->second
;
1233 // Delete only on a match as a host cookie.
1234 if (cc
->IsHostCookie() && cc
->IsDomainMatch(host
) &&
1235 cc
->CreationDate() >= delete_begin
&&
1236 // The assumption that null |delete_end| is equivalent to
1237 // Time::Max() is confusing.
1238 (delete_end
.is_null() || cc
->CreationDate() < delete_end
)) {
1241 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPLICIT
);
1247 int CookieMonster::DeleteAllForHost(const GURL
& url
) {
1248 return DeleteAllCreatedBetweenForHost(Time(), Time::Max(), url
);
1252 bool CookieMonster::DeleteCanonicalCookie(const CanonicalCookie
& cookie
) {
1253 base::AutoLock
autolock(lock_
);
1255 for (CookieMapItPair its
= cookies_
.equal_range(GetKey(cookie
.Domain()));
1256 its
.first
!= its
.second
; ++its
.first
) {
1257 // The creation date acts as our unique index...
1258 if (its
.first
->second
->CreationDate() == cookie
.CreationDate()) {
1259 InternalDeleteCookie(its
.first
, true, DELETE_COOKIE_EXPLICIT
);
1266 void CookieMonster::SetCookieableSchemes(const char* schemes
[],
1267 size_t num_schemes
) {
1268 base::AutoLock
autolock(lock_
);
1270 // Cookieable Schemes must be set before first use of function.
1271 DCHECK(!initialized_
);
1273 cookieable_schemes_
.clear();
1274 cookieable_schemes_
.insert(cookieable_schemes_
.end(),
1275 schemes
, schemes
+ num_schemes
);
1278 void CookieMonster::SetEnableFileScheme(bool accept
) {
1279 // This assumes "file" is always at the end of the array. See the comment
1280 // above kDefaultCookieableSchemes.
1281 int num_schemes
= accept
? kDefaultCookieableSchemesCount
:
1282 kDefaultCookieableSchemesCount
- 1;
1283 SetCookieableSchemes(kDefaultCookieableSchemes
, num_schemes
);
1286 void CookieMonster::SetKeepExpiredCookies() {
1287 keep_expired_cookies_
= true;
1290 void CookieMonster::FlushStore(const base::Closure
& callback
) {
1291 base::AutoLock
autolock(lock_
);
1292 if (initialized_
&& store_
.get())
1293 store_
->Flush(callback
);
1294 else if (!callback
.is_null())
1295 base::MessageLoop::current()->PostTask(FROM_HERE
, callback
);
1298 bool CookieMonster::SetCookieWithOptions(const GURL
& url
,
1299 const std::string
& cookie_line
,
1300 const CookieOptions
& options
) {
1301 base::AutoLock
autolock(lock_
);
1303 if (!HasCookieableScheme(url
)) {
1307 return SetCookieWithCreationTimeAndOptions(url
, cookie_line
, Time(), options
);
1310 std::string
CookieMonster::GetCookiesWithOptions(const GURL
& url
,
1311 const CookieOptions
& options
) {
1312 base::AutoLock
autolock(lock_
);
1314 if (!HasCookieableScheme(url
))
1315 return std::string();
1317 TimeTicks
start_time(TimeTicks::Now());
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 histogram_time_get_
->AddTime(TimeTicks::Now() - start_time
);
1327 VLOG(kVlogGetCookies
) << "GetCookies() result: " << cookie_line
;
1332 void CookieMonster::DeleteCookie(const GURL
& url
,
1333 const std::string
& cookie_name
) {
1334 base::AutoLock
autolock(lock_
);
1336 if (!HasCookieableScheme(url
))
1339 CookieOptions options
;
1340 options
.set_include_httponly();
1341 // Get the cookies for this host and its domain(s).
1342 std::vector
<CanonicalCookie
*> cookies
;
1343 FindCookiesForHostAndDomain(url
, options
, true, &cookies
);
1344 std::set
<CanonicalCookie
*> matching_cookies
;
1346 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookies
.begin();
1347 it
!= cookies
.end(); ++it
) {
1348 if ((*it
)->Name() != cookie_name
)
1350 if (url
.path().find((*it
)->Path()))
1352 matching_cookies
.insert(*it
);
1355 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1356 CookieMap::iterator curit
= it
;
1358 if (matching_cookies
.find(curit
->second
) != matching_cookies
.end()) {
1359 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPLICIT
);
1364 int CookieMonster::DeleteSessionCookies() {
1365 base::AutoLock
autolock(lock_
);
1367 int num_deleted
= 0;
1368 for (CookieMap::iterator it
= cookies_
.begin(); it
!= cookies_
.end();) {
1369 CookieMap::iterator curit
= it
;
1370 CanonicalCookie
* cc
= curit
->second
;
1373 if (!cc
->IsPersistent()) {
1374 InternalDeleteCookie(curit
,
1375 true, /*sync_to_store*/
1376 DELETE_COOKIE_EXPIRED
);
1384 bool CookieMonster::HasCookiesForETLDP1(const std::string
& etldp1
) {
1385 base::AutoLock
autolock(lock_
);
1387 const std::string
key(GetKey(etldp1
));
1389 CookieMapItPair its
= cookies_
.equal_range(key
);
1390 return its
.first
!= its
.second
;
1393 CookieMonster
* CookieMonster::GetCookieMonster() {
1397 // This function must be called before the CookieMonster is used.
1398 void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies
) {
1399 DCHECK(!initialized_
);
1400 persist_session_cookies_
= persist_session_cookies
;
1403 void CookieMonster::SetForceKeepSessionState() {
1405 store_
->SetForceKeepSessionState();
1409 CookieMonster::~CookieMonster() {
1413 bool CookieMonster::SetCookieWithCreationTime(const GURL
& url
,
1414 const std::string
& cookie_line
,
1415 const base::Time
& creation_time
) {
1416 DCHECK(!store_
.get()) << "This method is only to be used by unit-tests.";
1417 base::AutoLock
autolock(lock_
);
1419 if (!HasCookieableScheme(url
)) {
1424 return SetCookieWithCreationTimeAndOptions(url
, cookie_line
, creation_time
,
1428 void CookieMonster::InitStore() {
1429 DCHECK(store_
.get()) << "Store must exist to initialize";
1431 // We bind in the current time so that we can report the wall-clock time for
1433 store_
->Load(base::Bind(&CookieMonster::OnLoaded
, this, TimeTicks::Now()));
1436 void CookieMonster::OnLoaded(TimeTicks beginning_time
,
1437 const std::vector
<CanonicalCookie
*>& cookies
) {
1438 StoreLoadedCookies(cookies
);
1439 histogram_time_blocked_on_load_
->AddTime(TimeTicks::Now() - beginning_time
);
1441 // Invoke the task queue of cookie request.
1445 void CookieMonster::OnKeyLoaded(const std::string
& key
,
1446 const std::vector
<CanonicalCookie
*>& cookies
) {
1447 // This function does its own separate locking.
1448 StoreLoadedCookies(cookies
);
1450 std::deque
<scoped_refptr
<CookieMonsterTask
> > tasks_pending_for_key
;
1452 // We need to do this repeatedly until no more tasks were added to the queue
1453 // during the period where we release the lock.
1456 base::AutoLock
autolock(lock_
);
1457 std::map
<std::string
, std::deque
<scoped_refptr
<CookieMonsterTask
> > >
1458 ::iterator it
= tasks_pending_for_key_
.find(key
);
1459 if (it
== tasks_pending_for_key_
.end()) {
1460 keys_loaded_
.insert(key
);
1463 if (it
->second
.empty()) {
1464 keys_loaded_
.insert(key
);
1465 tasks_pending_for_key_
.erase(it
);
1468 it
->second
.swap(tasks_pending_for_key
);
1471 while (!tasks_pending_for_key
.empty()) {
1472 scoped_refptr
<CookieMonsterTask
> task
= tasks_pending_for_key
.front();
1474 tasks_pending_for_key
.pop_front();
1479 void CookieMonster::StoreLoadedCookies(
1480 const std::vector
<CanonicalCookie
*>& cookies
) {
1481 // Initialize the store and sync in any saved persistent cookies. We don't
1482 // care if it's expired, insert it so it can be garbage collected, removed,
1484 base::AutoLock
autolock(lock_
);
1486 CookieItVector cookies_with_control_chars
;
1488 for (std::vector
<CanonicalCookie
*>::const_iterator it
= cookies
.begin();
1489 it
!= cookies
.end(); ++it
) {
1490 int64 cookie_creation_time
= (*it
)->CreationDate().ToInternalValue();
1492 if (creation_times_
.insert(cookie_creation_time
).second
) {
1493 CookieMap::iterator inserted
=
1494 InternalInsertCookie(GetKey((*it
)->Domain()), *it
, false);
1495 const Time
cookie_access_time((*it
)->LastAccessDate());
1496 if (earliest_access_time_
.is_null() ||
1497 cookie_access_time
< earliest_access_time_
)
1498 earliest_access_time_
= cookie_access_time
;
1500 if (ContainsControlCharacter((*it
)->Name()) ||
1501 ContainsControlCharacter((*it
)->Value())) {
1502 cookies_with_control_chars
.push_back(inserted
);
1505 LOG(ERROR
) << base::StringPrintf("Found cookies with duplicate creation "
1506 "times in backing store: "
1507 "{name='%s', domain='%s', path='%s'}",
1508 (*it
)->Name().c_str(),
1509 (*it
)->Domain().c_str(),
1510 (*it
)->Path().c_str());
1511 // We've been given ownership of the cookie and are throwing it
1512 // away; reclaim the space.
1517 // Any cookies that contain control characters that we have loaded from the
1518 // persistent store should be deleted. See http://crbug.com/238041.
1519 for (CookieItVector::iterator it
= cookies_with_control_chars
.begin();
1520 it
!= cookies_with_control_chars
.end();) {
1521 CookieItVector::iterator curit
= it
;
1524 InternalDeleteCookie(*curit
, true, DELETE_COOKIE_CONTROL_CHAR
);
1527 // After importing cookies from the PersistentCookieStore, verify that
1528 // none of our other constraints are violated.
1529 // In particular, the backing store might have given us duplicate cookies.
1531 // This method could be called multiple times due to priority loading, thus
1532 // cookies loaded in previous runs will be validated again, but this is OK
1533 // since they are expected to be much fewer than total DB.
1534 EnsureCookiesMapIsValid();
1537 void CookieMonster::InvokeQueue() {
1539 scoped_refptr
<CookieMonsterTask
> request_task
;
1541 base::AutoLock
autolock(lock_
);
1542 if (tasks_pending_
.empty()) {
1544 creation_times_
.clear();
1545 keys_loaded_
.clear();
1548 request_task
= tasks_pending_
.front();
1549 tasks_pending_
.pop();
1551 request_task
->Run();
1555 void CookieMonster::EnsureCookiesMapIsValid() {
1556 lock_
.AssertAcquired();
1558 int num_duplicates_trimmed
= 0;
1560 // Iterate through all the of the cookies, grouped by host.
1561 CookieMap::iterator prev_range_end
= cookies_
.begin();
1562 while (prev_range_end
!= cookies_
.end()) {
1563 CookieMap::iterator cur_range_begin
= prev_range_end
;
1564 const std::string key
= cur_range_begin
->first
; // Keep a copy.
1565 CookieMap::iterator cur_range_end
= cookies_
.upper_bound(key
);
1566 prev_range_end
= cur_range_end
;
1568 // Ensure no equivalent cookies for this host.
1569 num_duplicates_trimmed
+=
1570 TrimDuplicateCookiesForKey(key
, cur_range_begin
, cur_range_end
);
1573 // Record how many duplicates were found in the database.
1574 // See InitializeHistograms() for details.
1575 histogram_cookie_deletion_cause_
->Add(num_duplicates_trimmed
);
1578 int CookieMonster::TrimDuplicateCookiesForKey(
1579 const std::string
& key
,
1580 CookieMap::iterator begin
,
1581 CookieMap::iterator end
) {
1582 lock_
.AssertAcquired();
1584 // Set of cookies ordered by creation time.
1585 typedef std::set
<CookieMap::iterator
, OrderByCreationTimeDesc
> CookieSet
;
1587 // Helper map we populate to find the duplicates.
1588 typedef std::map
<CookieSignature
, CookieSet
> EquivalenceMap
;
1589 EquivalenceMap equivalent_cookies
;
1591 // The number of duplicate cookies that have been found.
1592 int num_duplicates
= 0;
1594 // Iterate through all of the cookies in our range, and insert them into
1595 // the equivalence map.
1596 for (CookieMap::iterator it
= begin
; it
!= end
; ++it
) {
1597 DCHECK_EQ(key
, it
->first
);
1598 CanonicalCookie
* cookie
= it
->second
;
1600 CookieSignature
signature(cookie
->Name(), cookie
->Domain(),
1602 CookieSet
& set
= equivalent_cookies
[signature
];
1604 // We found a duplicate!
1608 // We save the iterator into |cookies_| rather than the actual cookie
1609 // pointer, since we may need to delete it later.
1610 bool insert_success
= set
.insert(it
).second
;
1611 DCHECK(insert_success
) <<
1612 "Duplicate creation times found in duplicate cookie name scan.";
1615 // If there were no duplicates, we are done!
1616 if (num_duplicates
== 0)
1619 // Make sure we find everything below that we did above.
1620 int num_duplicates_found
= 0;
1622 // Otherwise, delete all the duplicate cookies, both from our in-memory store
1623 // and from the backing store.
1624 for (EquivalenceMap::iterator it
= equivalent_cookies
.begin();
1625 it
!= equivalent_cookies
.end();
1627 const CookieSignature
& signature
= it
->first
;
1628 CookieSet
& dupes
= it
->second
;
1630 if (dupes
.size() <= 1)
1631 continue; // This cookiename/path has no duplicates.
1632 num_duplicates_found
+= dupes
.size() - 1;
1634 // Since |dups| is sorted by creation time (descending), the first cookie
1635 // is the most recent one, so we will keep it. The rest are duplicates.
1636 dupes
.erase(dupes
.begin());
1638 LOG(ERROR
) << base::StringPrintf(
1639 "Found %d duplicate cookies for host='%s', "
1640 "with {name='%s', domain='%s', path='%s'}",
1641 static_cast<int>(dupes
.size()),
1643 signature
.name
.c_str(),
1644 signature
.domain
.c_str(),
1645 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();
1651 dupes_it
!= dupes
.end();
1653 InternalDeleteCookie(*dupes_it
, true,
1654 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
);
1657 DCHECK_EQ(num_duplicates
, num_duplicates_found
);
1659 return num_duplicates
;
1662 // Note: file must be the last scheme.
1663 const char* CookieMonster::kDefaultCookieableSchemes
[] =
1664 { "http", "https", "ws", "wss", "file" };
1665 const int CookieMonster::kDefaultCookieableSchemesCount
=
1666 arraysize(kDefaultCookieableSchemes
);
1668 void CookieMonster::SetDefaultCookieableSchemes() {
1669 // Always disable file scheme unless SetEnableFileScheme(true) is called.
1670 SetCookieableSchemes(kDefaultCookieableSchemes
,
1671 kDefaultCookieableSchemesCount
- 1);
1674 void CookieMonster::FindCookiesForHostAndDomain(
1676 const CookieOptions
& options
,
1677 bool update_access_time
,
1678 std::vector
<CanonicalCookie
*>* cookies
) {
1679 lock_
.AssertAcquired();
1681 const Time
current_time(CurrentTime());
1683 // Probe to save statistics relatively frequently. We do it here rather
1684 // than in the set path as many websites won't set cookies, and we
1685 // want to collect statistics whenever the browser's being used.
1686 RecordPeriodicStats(current_time
);
1688 // Can just dispatch to FindCookiesForKey
1689 const std::string
key(GetKey(url
.host()));
1690 FindCookiesForKey(key
, url
, options
, current_time
,
1691 update_access_time
, cookies
);
1694 void CookieMonster::FindCookiesForKey(const std::string
& key
,
1696 const CookieOptions
& options
,
1697 const Time
& current
,
1698 bool update_access_time
,
1699 std::vector
<CanonicalCookie
*>* cookies
) {
1700 lock_
.AssertAcquired();
1702 for (CookieMapItPair its
= cookies_
.equal_range(key
);
1703 its
.first
!= its
.second
; ) {
1704 CookieMap::iterator curit
= its
.first
;
1705 CanonicalCookie
* cc
= curit
->second
;
1708 // If the cookie is expired, delete it.
1709 if (cc
->IsExpired(current
) && !keep_expired_cookies_
) {
1710 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPIRED
);
1714 // Filter out cookies that should not be included for a request to the
1715 // given |url|. HTTP only cookies are filtered depending on the passed
1716 // cookie |options|.
1717 if (!cc
->IncludeForRequestURL(url
, options
))
1720 // Add this cookie to the set of matching cookies. Update the access
1721 // time if we've been requested to do so.
1722 if (update_access_time
) {
1723 InternalUpdateCookieAccessTime(cc
, current
);
1725 cookies
->push_back(cc
);
1729 bool CookieMonster::DeleteAnyEquivalentCookie(const std::string
& key
,
1730 const CanonicalCookie
& ecc
,
1732 bool already_expired
) {
1733 lock_
.AssertAcquired();
1735 bool found_equivalent_cookie
= false;
1736 bool skipped_httponly
= false;
1737 for (CookieMapItPair its
= cookies_
.equal_range(key
);
1738 its
.first
!= its
.second
; ) {
1739 CookieMap::iterator curit
= its
.first
;
1740 CanonicalCookie
* cc
= curit
->second
;
1743 if (ecc
.IsEquivalent(*cc
)) {
1744 // We should never have more than one equivalent cookie, since they should
1745 // overwrite each other.
1746 CHECK(!found_equivalent_cookie
) <<
1747 "Duplicate equivalent cookies found, cookie store is corrupted.";
1748 if (skip_httponly
&& cc
->IsHttpOnly()) {
1749 skipped_httponly
= true;
1751 InternalDeleteCookie(curit
, true, already_expired
?
1752 DELETE_COOKIE_EXPIRED_OVERWRITE
: DELETE_COOKIE_OVERWRITE
);
1754 found_equivalent_cookie
= true;
1757 return skipped_httponly
;
1760 CookieMonster::CookieMap::iterator
CookieMonster::InternalInsertCookie(
1761 const std::string
& key
,
1762 CanonicalCookie
* cc
,
1763 bool sync_to_store
) {
1764 lock_
.AssertAcquired();
1766 if ((cc
->IsPersistent() || persist_session_cookies_
) && store_
.get() &&
1768 store_
->AddCookie(*cc
);
1769 CookieMap::iterator inserted
=
1770 cookies_
.insert(CookieMap::value_type(key
, cc
));
1771 if (delegate_
.get()) {
1772 delegate_
->OnCookieChanged(
1773 *cc
, false, CookieMonsterDelegate::CHANGE_COOKIE_EXPLICIT
);
1779 bool CookieMonster::SetCookieWithCreationTimeAndOptions(
1781 const std::string
& cookie_line
,
1782 const Time
& creation_time_or_null
,
1783 const CookieOptions
& options
) {
1784 lock_
.AssertAcquired();
1786 VLOG(kVlogSetCookies
) << "SetCookie() line: " << cookie_line
;
1788 Time creation_time
= creation_time_or_null
;
1789 if (creation_time
.is_null()) {
1790 creation_time
= CurrentTime();
1791 last_time_seen_
= creation_time
;
1794 scoped_ptr
<CanonicalCookie
> cc(
1795 CanonicalCookie::Create(url
, cookie_line
, creation_time
, options
));
1798 VLOG(kVlogSetCookies
) << "WARNING: Failed to allocate CanonicalCookie";
1801 return SetCanonicalCookie(&cc
, creation_time
, options
);
1804 bool CookieMonster::SetCanonicalCookie(scoped_ptr
<CanonicalCookie
>* cc
,
1805 const Time
& creation_time
,
1806 const CookieOptions
& options
) {
1807 const std::string
key(GetKey((*cc
)->Domain()));
1808 bool already_expired
= (*cc
)->IsExpired(creation_time
);
1809 if (DeleteAnyEquivalentCookie(key
, **cc
, options
.exclude_httponly(),
1811 VLOG(kVlogSetCookies
) << "SetCookie() not clobbering httponly cookie";
1815 VLOG(kVlogSetCookies
) << "SetCookie() key: " << key
<< " cc: "
1816 << (*cc
)->DebugString();
1818 // Realize that we might be setting an expired cookie, and the only point
1819 // was to delete the cookie which we've already done.
1820 if (!already_expired
|| keep_expired_cookies_
) {
1821 // See InitializeHistograms() for details.
1822 if ((*cc
)->IsPersistent()) {
1823 histogram_expiration_duration_minutes_
->Add(
1824 ((*cc
)->ExpiryDate() - creation_time
).InMinutes());
1827 InternalInsertCookie(key
, cc
->release(), true);
1829 VLOG(kVlogSetCookies
) << "SetCookie() not storing already expired cookie.";
1832 // We assume that hopefully setting a cookie will be less common than
1833 // querying a cookie. Since setting a cookie can put us over our limits,
1834 // make sure that we garbage collect... We can also make the assumption that
1835 // if a cookie was set, in the common case it will be used soon after,
1836 // and we will purge the expired cookies in GetCookies().
1837 GarbageCollect(creation_time
, key
);
1842 void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie
* cc
,
1843 const Time
& current
) {
1844 lock_
.AssertAcquired();
1846 // Based off the Mozilla code. When a cookie has been accessed recently,
1847 // don't bother updating its access time again. This reduces the number of
1848 // updates we do during pageload, which in turn reduces the chance our storage
1849 // backend will hit its batch thresholds and be forced to update.
1850 if ((current
- cc
->LastAccessDate()) < last_access_threshold_
)
1853 // See InitializeHistograms() for details.
1854 histogram_between_access_interval_minutes_
->Add(
1855 (current
- cc
->LastAccessDate()).InMinutes());
1857 cc
->SetLastAccessDate(current
);
1858 if ((cc
->IsPersistent() || persist_session_cookies_
) && store_
.get())
1859 store_
->UpdateCookieAccessTime(*cc
);
1862 // InternalDeleteCookies must not invalidate iterators other than the one being
1864 void CookieMonster::InternalDeleteCookie(CookieMap::iterator it
,
1866 DeletionCause deletion_cause
) {
1867 lock_
.AssertAcquired();
1869 // Ideally, this would be asserted up where we define ChangeCauseMapping,
1870 // but DeletionCause's visibility (or lack thereof) forces us to make
1872 COMPILE_ASSERT(arraysize(ChangeCauseMapping
) == DELETE_COOKIE_LAST_ENTRY
+ 1,
1873 ChangeCauseMapping_size_not_eq_DeletionCause_enum_size
);
1875 // See InitializeHistograms() for details.
1876 if (deletion_cause
!= DELETE_COOKIE_DONT_RECORD
)
1877 histogram_cookie_deletion_cause_
->Add(deletion_cause
);
1879 CanonicalCookie
* cc
= it
->second
;
1880 VLOG(kVlogSetCookies
) << "InternalDeleteCookie() cc: " << cc
->DebugString();
1882 if ((cc
->IsPersistent() || persist_session_cookies_
) && store_
.get() &&
1884 store_
->DeleteCookie(*cc
);
1885 if (delegate_
.get()) {
1886 ChangeCausePair mapping
= ChangeCauseMapping
[deletion_cause
];
1889 delegate_
->OnCookieChanged(*cc
, true, mapping
.cause
);
1895 // Domain expiry behavior is unchanged by key/expiry scheme (the
1896 // meaning of the key is different, but that's not visible to this routine).
1897 int CookieMonster::GarbageCollect(const Time
& current
,
1898 const std::string
& key
) {
1899 lock_
.AssertAcquired();
1901 int num_deleted
= 0;
1903 Time::Now() - TimeDelta::FromDays(kSafeFromGlobalPurgeDays
));
1905 // Collect garbage for this key, minding cookie priorities.
1906 if (cookies_
.count(key
) > kDomainMaxCookies
) {
1907 VLOG(kVlogGarbageCollection
) << "GarbageCollect() key: " << key
;
1909 CookieItVector cookie_its
;
1910 num_deleted
+= GarbageCollectExpired(
1911 current
, cookies_
.equal_range(key
), &cookie_its
);
1912 if (cookie_its
.size() > kDomainMaxCookies
) {
1913 VLOG(kVlogGarbageCollection
) << "Deep Garbage Collect domain.";
1915 cookie_its
.size() - (kDomainMaxCookies
- kDomainPurgeCookies
);
1916 DCHECK(purge_goal
> kDomainPurgeCookies
);
1918 // Boundary iterators into |cookie_its| for different priorities.
1919 CookieItVector::iterator it_bdd
[4];
1920 // Intialize |it_bdd| while sorting |cookie_its| by priorities.
1921 // Schematic: [MLLHMHHLMM] => [LLL|MMMM|HHH], with 4 boundaries.
1922 it_bdd
[0] = cookie_its
.begin();
1923 it_bdd
[3] = cookie_its
.end();
1924 it_bdd
[1] = PartitionCookieByPriority(it_bdd
[0], it_bdd
[3],
1925 COOKIE_PRIORITY_LOW
);
1926 it_bdd
[2] = PartitionCookieByPriority(it_bdd
[1], it_bdd
[3],
1927 COOKIE_PRIORITY_MEDIUM
);
1929 kDomainCookiesQuotaLow
,
1930 kDomainCookiesQuotaMedium
,
1931 kDomainCookiesQuotaHigh
1934 // Purge domain cookies in 3 rounds.
1935 // Round 1: consider low-priority cookies only: evict least-recently
1936 // accessed, while protecting quota[0] of these from deletion.
1937 // Round 2: consider {low, medium}-priority cookies, evict least-recently
1938 // accessed, while protecting quota[0] + quota[1].
1939 // Round 3: consider all cookies, evict least-recently accessed.
1940 size_t accumulated_quota
= 0;
1941 CookieItVector::iterator it_purge_begin
= it_bdd
[0];
1942 for (int i
= 0; i
< 3 && purge_goal
> 0; ++i
) {
1943 accumulated_quota
+= quota
[i
];
1945 size_t num_considered
= it_bdd
[i
+ 1] - it_purge_begin
;
1946 if (num_considered
<= accumulated_quota
)
1949 // Number of cookies that will be purged in this round.
1951 std::min(purge_goal
, num_considered
- accumulated_quota
);
1952 purge_goal
-= round_goal
;
1954 SortLeastRecentlyAccessed(it_purge_begin
, it_bdd
[i
+ 1], round_goal
);
1955 // Cookies accessed on or after |safe_date| would have been safe from
1956 // global purge, and we want to keep track of this.
1957 CookieItVector::iterator it_purge_end
= it_purge_begin
+ round_goal
;
1958 CookieItVector::iterator it_purge_middle
=
1959 LowerBoundAccessDate(it_purge_begin
, it_purge_end
, safe_date
);
1960 // Delete cookies accessed before |safe_date|.
1961 num_deleted
+= GarbageCollectDeleteRange(
1963 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
,
1966 // Delete cookies accessed on or after |safe_date|.
1967 num_deleted
+= GarbageCollectDeleteRange(
1969 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
,
1972 it_purge_begin
= it_purge_end
;
1974 DCHECK_EQ(0U, purge_goal
);
1978 // Collect garbage for everything. With firefox style we want to preserve
1979 // cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
1980 if (cookies_
.size() > kMaxCookies
&&
1981 earliest_access_time_
< safe_date
) {
1982 VLOG(kVlogGarbageCollection
) << "GarbageCollect() everything";
1983 CookieItVector cookie_its
;
1984 num_deleted
+= GarbageCollectExpired(
1985 current
, CookieMapItPair(cookies_
.begin(), cookies_
.end()),
1987 if (cookie_its
.size() > kMaxCookies
) {
1988 VLOG(kVlogGarbageCollection
) << "Deep Garbage Collect everything.";
1989 size_t purge_goal
= cookie_its
.size() - (kMaxCookies
- kPurgeCookies
);
1990 DCHECK(purge_goal
> kPurgeCookies
);
1991 // Sorts up to *and including* |cookie_its[purge_goal]|, so
1992 // |earliest_access_time| will be properly assigned even if
1993 // |global_purge_it| == |cookie_its.begin() + purge_goal|.
1994 SortLeastRecentlyAccessed(cookie_its
.begin(), cookie_its
.end(),
1996 // Find boundary to cookies older than safe_date.
1997 CookieItVector::iterator global_purge_it
=
1998 LowerBoundAccessDate(cookie_its
.begin(),
1999 cookie_its
.begin() + purge_goal
,
2001 // Only delete the old cookies.
2002 num_deleted
+= GarbageCollectDeleteRange(
2004 DELETE_COOKIE_EVICTED_GLOBAL
,
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(
2016 const Time
& current
,
2017 const CookieMapItPair
& itpair
,
2018 CookieItVector
* cookie_its
) {
2019 if (keep_expired_cookies_
)
2022 lock_
.AssertAcquired();
2024 int num_deleted
= 0;
2025 for (CookieMap::iterator it
= itpair
.first
, end
= itpair
.second
; it
!= end
;) {
2026 CookieMap::iterator curit
= it
;
2029 if (curit
->second
->IsExpired(current
)) {
2030 InternalDeleteCookie(curit
, true, DELETE_COOKIE_EXPIRED
);
2032 } else if (cookie_its
) {
2033 cookie_its
->push_back(curit
);
2040 int CookieMonster::GarbageCollectDeleteRange(
2041 const Time
& current
,
2042 DeletionCause cause
,
2043 CookieItVector::iterator it_begin
,
2044 CookieItVector::iterator it_end
) {
2045 for (CookieItVector::iterator it
= it_begin
; it
!= it_end
; it
++) {
2046 histogram_evicted_last_access_minutes_
->Add(
2047 (current
- (*it
)->second
->LastAccessDate()).InMinutes());
2048 InternalDeleteCookie((*it
), true, cause
);
2050 return it_end
- it_begin
;
2053 // A wrapper around registry_controlled_domains::GetDomainAndRegistry
2054 // to make clear we're creating a key for our local map. Here and
2055 // in FindCookiesForHostAndDomain() are the only two places where
2056 // we need to conditionalize based on key type.
2058 // Note that this key algorithm explicitly ignores the scheme. This is
2059 // because when we're entering cookies into the map from the backing store,
2060 // we in general won't have the scheme at that point.
2061 // In practical terms, this means that file cookies will be stored
2062 // in the map either by an empty string or by UNC name (and will be
2063 // limited by kMaxCookiesPerHost), and extension cookies will be stored
2064 // based on the single extension id, as the extension id won't have the
2065 // form of a DNS host and hence GetKey() will return it unchanged.
2067 // Arguably the right thing to do here is to make the key
2068 // algorithm dependent on the scheme, and make sure that the scheme is
2069 // available everywhere the key must be obtained (specfically at backing
2070 // store load time). This would require either changing the backing store
2071 // database schema to include the scheme (far more trouble than it's worth), or
2072 // separating out file cookies into their own CookieMonster instance and
2073 // thus restricting each scheme to a single cookie monster (which might
2074 // be worth it, but is still too much trouble to solve what is currently a
2076 std::string
CookieMonster::GetKey(const std::string
& domain
) const {
2077 std::string
effective_domain(
2078 registry_controlled_domains::GetDomainAndRegistry(
2079 domain
, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
));
2080 if (effective_domain
.empty())
2081 effective_domain
= domain
;
2083 if (!effective_domain
.empty() && effective_domain
[0] == '.')
2084 return effective_domain
.substr(1);
2085 return effective_domain
;
2088 bool CookieMonster::IsCookieableScheme(const std::string
& scheme
) {
2089 base::AutoLock
autolock(lock_
);
2091 return std::find(cookieable_schemes_
.begin(), cookieable_schemes_
.end(),
2092 scheme
) != cookieable_schemes_
.end();
2095 bool CookieMonster::HasCookieableScheme(const GURL
& url
) {
2096 lock_
.AssertAcquired();
2098 // Make sure the request is on a cookie-able url scheme.
2099 for (size_t i
= 0; i
< cookieable_schemes_
.size(); ++i
) {
2100 // We matched a scheme.
2101 if (url
.SchemeIs(cookieable_schemes_
[i
].c_str())) {
2102 // We've matched a supported scheme.
2107 // The scheme didn't match any in our whitelist.
2108 VLOG(kVlogPerCookieMonster
) << "WARNING: Unsupported cookie scheme: "
2113 // Test to see if stats should be recorded, and record them if so.
2114 // The goal here is to get sampling for the average browser-hour of
2115 // activity. We won't take samples when the web isn't being surfed,
2116 // and when the web is being surfed, we'll take samples about every
2117 // kRecordStatisticsIntervalSeconds.
2118 // last_statistic_record_time_ is initialized to Now() rather than null
2119 // in the constructor so that we won't take statistics right after
2120 // startup, to avoid bias from browsers that are started but not used.
2121 void CookieMonster::RecordPeriodicStats(const base::Time
& current_time
) {
2122 const base::TimeDelta
kRecordStatisticsIntervalTime(
2123 base::TimeDelta::FromSeconds(kRecordStatisticsIntervalSeconds
));
2125 // If we've taken statistics recently, return.
2126 if (current_time
- last_statistic_record_time_
<=
2127 kRecordStatisticsIntervalTime
) {
2131 // See InitializeHistograms() for details.
2132 histogram_count_
->Add(cookies_
.size());
2134 // More detailed statistics on cookie counts at different granularities.
2135 TimeTicks
beginning_of_time(TimeTicks::Now());
2137 for (CookieMap::const_iterator it_key
= cookies_
.begin();
2138 it_key
!= cookies_
.end(); ) {
2139 const std::string
& key(it_key
->first
);
2142 typedef std::map
<std::string
, unsigned int> DomainMap
;
2143 DomainMap domain_map
;
2144 CookieMapItPair its_cookies
= cookies_
.equal_range(key
);
2145 while (its_cookies
.first
!= its_cookies
.second
) {
2147 const std::string
& cookie_domain(its_cookies
.first
->second
->Domain());
2148 domain_map
[cookie_domain
]++;
2150 its_cookies
.first
++;
2152 histogram_etldp1_count_
->Add(key_count
);
2153 histogram_domain_per_etldp1_count_
->Add(domain_map
.size());
2154 for (DomainMap::const_iterator domain_map_it
= domain_map
.begin();
2155 domain_map_it
!= domain_map
.end(); domain_map_it
++)
2156 histogram_domain_count_
->Add(domain_map_it
->second
);
2158 it_key
= its_cookies
.second
;
2162 << "Time for recording cookie stats (us): "
2163 << (TimeTicks::Now() - beginning_of_time
).InMicroseconds();
2165 last_statistic_record_time_
= current_time
;
2168 // Initialize all histogram counter variables used in this class.
2170 // Normal histogram usage involves using the macros defined in
2171 // histogram.h, which automatically takes care of declaring these
2172 // variables (as statics), initializing them, and accumulating into
2173 // them, all from a single entry point. Unfortunately, that solution
2174 // doesn't work for the CookieMonster, as it's vulnerable to races between
2175 // separate threads executing the same functions and hence initializing the
2176 // same static variables. There isn't a race danger in the histogram
2177 // accumulation calls; they are written to be resilient to simultaneous
2178 // calls from multiple threads.
2180 // The solution taken here is to have per-CookieMonster instance
2181 // variables that are constructed during CookieMonster construction.
2182 // Note that these variables refer to the same underlying histogram,
2183 // so we still race (but safely) with other CookieMonster instances
2184 // for accumulation.
2186 // To do this we've expanded out the individual histogram macros calls,
2187 // with declarations of the variables in the class decl, initialization here
2188 // (done from the class constructor) and direct calls to the accumulation
2189 // methods where needed. The specific histogram macro calls on which the
2190 // initialization is based are included in comments below.
2191 void CookieMonster::InitializeHistograms() {
2192 // From UMA_HISTOGRAM_CUSTOM_COUNTS
2193 histogram_expiration_duration_minutes_
= base::Histogram::FactoryGet(
2194 "Cookie.ExpirationDurationMinutes",
2195 1, kMinutesInTenYears
, 50,
2196 base::Histogram::kUmaTargetedHistogramFlag
);
2197 histogram_between_access_interval_minutes_
= base::Histogram::FactoryGet(
2198 "Cookie.BetweenAccessIntervalMinutes",
2199 1, kMinutesInTenYears
, 50,
2200 base::Histogram::kUmaTargetedHistogramFlag
);
2201 histogram_evicted_last_access_minutes_
= base::Histogram::FactoryGet(
2202 "Cookie.EvictedLastAccessMinutes",
2203 1, kMinutesInTenYears
, 50,
2204 base::Histogram::kUmaTargetedHistogramFlag
);
2205 histogram_count_
= base::Histogram::FactoryGet(
2206 "Cookie.Count", 1, 4000, 50,
2207 base::Histogram::kUmaTargetedHistogramFlag
);
2208 histogram_domain_count_
= base::Histogram::FactoryGet(
2209 "Cookie.DomainCount", 1, 4000, 50,
2210 base::Histogram::kUmaTargetedHistogramFlag
);
2211 histogram_etldp1_count_
= base::Histogram::FactoryGet(
2212 "Cookie.Etldp1Count", 1, 4000, 50,
2213 base::Histogram::kUmaTargetedHistogramFlag
);
2214 histogram_domain_per_etldp1_count_
= base::Histogram::FactoryGet(
2215 "Cookie.DomainPerEtldp1Count", 1, 4000, 50,
2216 base::Histogram::kUmaTargetedHistogramFlag
);
2218 // From UMA_HISTOGRAM_COUNTS_10000 & UMA_HISTOGRAM_CUSTOM_COUNTS
2219 histogram_number_duplicate_db_cookies_
= base::Histogram::FactoryGet(
2220 "Net.NumDuplicateCookiesInDb", 1, 10000, 50,
2221 base::Histogram::kUmaTargetedHistogramFlag
);
2223 // From UMA_HISTOGRAM_ENUMERATION
2224 histogram_cookie_deletion_cause_
= base::LinearHistogram::FactoryGet(
2225 "Cookie.DeletionCause", 1,
2226 DELETE_COOKIE_LAST_ENTRY
- 1, DELETE_COOKIE_LAST_ENTRY
,
2227 base::Histogram::kUmaTargetedHistogramFlag
);
2229 // From UMA_HISTOGRAM_{CUSTOM_,}TIMES
2230 histogram_time_get_
= base::Histogram::FactoryTimeGet("Cookie.TimeGet",
2231 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
2232 50, base::Histogram::kUmaTargetedHistogramFlag
);
2233 histogram_time_blocked_on_load_
= base::Histogram::FactoryTimeGet(
2234 "Cookie.TimeBlockedOnLoad",
2235 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(1),
2236 50, base::Histogram::kUmaTargetedHistogramFlag
);
2240 // The system resolution is not high enough, so we can have multiple
2241 // set cookies that result in the same system time. When this happens, we
2242 // increment by one Time unit. Let's hope computers don't get too fast.
2243 Time
CookieMonster::CurrentTime() {
2244 return std::max(Time::Now(),
2245 Time::FromInternalValue(last_time_seen_
.ToInternalValue() + 1));