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 // Brought to you by the letter D and the number 2.
7 #ifndef NET_COOKIES_COOKIE_MONSTER_H_
8 #define NET_COOKIES_COOKIE_MONSTER_H_
18 #include "base/basictypes.h"
19 #include "base/callback_forward.h"
20 #include "base/gtest_prod_util.h"
21 #include "base/memory/linked_ptr.h"
22 #include "base/memory/ref_counted.h"
23 #include "base/memory/scoped_ptr.h"
24 #include "base/synchronization/lock.h"
25 #include "base/time/time.h"
26 #include "net/base/net_export.h"
27 #include "net/cookies/canonical_cookie.h"
28 #include "net/cookies/cookie_constants.h"
29 #include "net/cookies/cookie_store.h"
40 class CookieMonsterDelegate
;
43 // The cookie monster is the system for storing and retrieving cookies. It has
44 // an in-memory list of all cookies, and synchronizes non-session cookies to an
45 // optional permanent storage that implements the PersistentCookieStore
48 // This class IS thread-safe. Normally, it is only used on the I/O thread, but
49 // is also accessed directly through Automation for UI testing.
51 // All cookie tasks are handled asynchronously. Tasks may be deferred if
52 // all affected cookies are not yet loaded from the backing store. Otherwise,
53 // the callback may be invoked immediately (prior to return of the asynchronous
56 // A cookie task is either pending loading of the entire cookie store, or
57 // loading of cookies for a specfic domain key(eTLD+1). In the former case, the
58 // cookie task will be queued in tasks_pending_ while PersistentCookieStore
59 // chain loads the cookie store on DB thread. In the latter case, the cookie
60 // task will be queued in tasks_pending_for_key_ while PermanentCookieStore
61 // loads cookies for the specified domain key(eTLD+1) on DB thread.
63 // Callbacks are guaranteed to be invoked on the calling thread.
65 // TODO(deanm) Implement CookieMonster, the cookie database.
66 // - Verify that our domain enforcement and non-dotted handling is correct
67 class NET_EXPORT CookieMonster
: public CookieStore
{
69 class PersistentCookieStore
;
70 typedef CookieMonsterDelegate Delegate
;
73 // * The 'top level domain' (TLD) of an internet domain name is
74 // the terminal "." free substring (e.g. "com" for google.com
76 // * The 'effective top level domain' (eTLD) is the longest
77 // "." initiated terminal substring of an internet domain name
78 // that is controlled by a general domain registrar.
79 // (e.g. "co.uk" for news.bbc.co.uk).
80 // * The 'effective top level domain plus one' (eTLD+1) is the
81 // shortest "." delimited terminal substring of an internet
82 // domain name that is not controlled by a general domain
83 // registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
84 // "google.com" for news.google.com). The general assumption
85 // is that all hosts and domains under an eTLD+1 share some
86 // administrative control.
88 // CookieMap is the central data structure of the CookieMonster. It
89 // is a map whose values are pointers to CanonicalCookie data
90 // structures (the data structures are owned by the CookieMonster
91 // and must be destroyed when removed from the map). The key is based on the
92 // effective domain of the cookies. If the domain of the cookie has an
93 // eTLD+1, that is the key for the map. If the domain of the cookie does not
94 // have an eTLD+1, the key of the map is the host the cookie applies to (it is
95 // not legal to have domain cookies without an eTLD+1). This rule
96 // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
97 // This behavior is the same as the behavior in Firefox v 3.6.10.
100 // I benchmarked hash_multimap vs multimap. We're going to be query-heavy
101 // so it would seem like hashing would help. However they were very
102 // close, with multimap being a tiny bit faster. I think this is because
103 // our map is at max around 1000 entries, and the additional complexity
104 // for the hashing might not overcome the O(log(1000)) for querying
105 // a multimap. Also, multimap is standard, another reason to use it.
106 // TODO(rdsmith): This benchmark should be re-done now that we're allowing
107 // subtantially more entries in the map.
108 typedef std::multimap
<std::string
, CanonicalCookie
*> CookieMap
;
109 typedef std::pair
<CookieMap::iterator
, CookieMap::iterator
> CookieMapItPair
;
110 typedef std::vector
<CookieMap::iterator
> CookieItVector
;
112 // Cookie garbage collection thresholds. Based off of the Mozilla defaults.
113 // When the number of cookies gets to k{Domain,}MaxCookies
114 // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
115 // It might seem scary to have a high purge value, but really it's not.
116 // You just make sure that you increase the max to cover the increase
117 // in purge, and we would have been purging the same number of cookies.
118 // We're just going through the garbage collection process less often.
119 // Note that the DOMAIN values are per eTLD+1; see comment for the
120 // CookieMap typedef. So, e.g., the maximum number of cookies allowed for
121 // google.com and all of its subdomains will be 150-180.
123 // Any cookies accessed more recently than kSafeFromGlobalPurgeDays will not
124 // be evicted by global garbage collection, even if we have more than
125 // kMaxCookies. This does not affect domain garbage collection.
126 static const size_t kDomainMaxCookies
;
127 static const size_t kDomainPurgeCookies
;
128 static const size_t kMaxCookies
;
129 static const size_t kPurgeCookies
;
131 // Quota for cookies with {low, medium, high} priorities within a domain.
132 static const size_t kDomainCookiesQuotaLow
;
133 static const size_t kDomainCookiesQuotaMedium
;
134 static const size_t kDomainCookiesQuotaHigh
;
136 // The store passed in should not have had Init() called on it yet. This
137 // class will take care of initializing it. The backing store is NOT owned by
138 // this class, but it must remain valid for the duration of the cookie
139 // monster's existence. If |store| is NULL, then no backing store will be
140 // updated. If |delegate| is non-NULL, it will be notified on
141 // creation/deletion of cookies.
142 CookieMonster(PersistentCookieStore
* store
, CookieMonsterDelegate
* delegate
);
144 // Only used during unit testing.
145 CookieMonster(PersistentCookieStore
* store
,
146 CookieMonsterDelegate
* delegate
,
147 int last_access_threshold_milliseconds
);
149 // Helper function that adds all cookies from |list| into this instance,
150 // overwriting any equivalent cookies.
151 bool ImportCookies(const CookieList
& list
);
153 typedef base::Callback
<void(const CookieList
& cookies
)> GetCookieListCallback
;
154 typedef base::Callback
<void(bool success
)> DeleteCookieCallback
;
155 typedef base::Callback
<void(bool cookies_exist
)> HasCookiesForETLDP1Callback
;
157 // Sets a cookie given explicit user-provided cookie attributes. The cookie
158 // name, value, domain, etc. are each provided as separate strings. This
159 // function expects each attribute to be well-formed. It will check for
160 // disallowed characters (e.g. the ';' character is disallowed within the
161 // cookie value attribute) and will return false without setting the cookie
162 // if such characters are found.
163 void SetCookieWithDetailsAsync(const GURL
& url
,
164 const std::string
& name
,
165 const std::string
& value
,
166 const std::string
& domain
,
167 const std::string
& path
,
168 const base::Time
& expiration_time
,
172 CookiePriority priority
,
173 const SetCookiesCallback
& callback
);
175 // Returns all the cookies, for use in management UI, etc. This does not mark
176 // the cookies as having been accessed.
177 // The returned cookies are ordered by longest path, then by earliest
179 void GetAllCookiesAsync(const GetCookieListCallback
& callback
);
181 // Returns all the cookies, for use in management UI, etc. Filters results
182 // using given url scheme, host / domain and path and options. This does not
183 // mark the cookies as having been accessed.
184 // The returned cookies are ordered by longest path, then earliest
186 void GetAllCookiesForURLWithOptionsAsync(
188 const CookieOptions
& options
,
189 const GetCookieListCallback
& callback
);
191 // Deletes all of the cookies.
192 void DeleteAllAsync(const DeleteCallback
& callback
);
194 // Deletes all cookies that match the host of the given URL
195 // regardless of path. This includes all http_only and secure cookies,
196 // but does not include any domain cookies that may apply to this host.
197 // Returns the number of cookies deleted.
198 void DeleteAllForHostAsync(const GURL
& url
, const DeleteCallback
& callback
);
200 // Deletes one specific cookie.
201 void DeleteCanonicalCookieAsync(const CanonicalCookie
& cookie
,
202 const DeleteCookieCallback
& callback
);
204 // Checks whether for a given ETLD+1, there currently exist any cookies.
205 void HasCookiesForETLDP1Async(const std::string
& etldp1
,
206 const HasCookiesForETLDP1Callback
& callback
);
208 // Resets the list of cookieable schemes to the supplied schemes.
209 // If this this method is called, it must be called before first use of
210 // the instance (i.e. as part of the instance initialization process).
211 void SetCookieableSchemes(const char* const schemes
[], size_t num_schemes
);
213 // Instructs the cookie monster to not delete expired cookies. This is used
214 // in cases where the cookie monster is used as a data structure to keep
215 // arbitrary cookies.
216 void SetKeepExpiredCookies();
218 // Protects session cookies from deletion on shutdown.
219 void SetForceKeepSessionState();
221 // Flush the backing store (if any) to disk and post the given callback when
223 // WARNING: THE CALLBACK WILL RUN ON A RANDOM THREAD. IT MUST BE THREAD SAFE.
224 // It may be posted to the current thread, or it may run on the thread that
225 // actually does the flushing. Your Task should generally post a notification
226 // to the thread you actually want to be notified on.
227 void FlushStore(const base::Closure
& callback
);
229 // Replaces all the cookies by |list|. This method does not flush the backend.
230 void SetAllCookiesAsync(const CookieList
& list
,
231 const SetCookiesCallback
& callback
);
233 // CookieStore implementation.
235 // Sets the cookies specified by |cookie_list| returned from |url|
236 // with options |options| in effect.
237 void SetCookieWithOptionsAsync(const GURL
& url
,
238 const std::string
& cookie_line
,
239 const CookieOptions
& options
,
240 const SetCookiesCallback
& callback
) override
;
242 // Gets all cookies that apply to |url| given |options|.
243 // The returned cookies are ordered by longest path, then earliest
245 void GetCookiesWithOptionsAsync(const GURL
& url
,
246 const CookieOptions
& options
,
247 const GetCookiesCallback
& callback
) override
;
249 // Invokes GetAllCookiesForURLWithOptions with options set to include HTTP
251 void GetAllCookiesForURLAsync(const GURL
& url
,
252 const GetCookieListCallback
& callback
) override
;
254 // Deletes all cookies with that might apply to |url| that has |cookie_name|.
255 void DeleteCookieAsync(const GURL
& url
,
256 const std::string
& cookie_name
,
257 const base::Closure
& callback
) override
;
259 // Deletes all of the cookies that have a creation_date greater than or equal
260 // to |delete_begin| and less than |delete_end|.
261 // Returns the number of cookies that have been deleted.
262 void DeleteAllCreatedBetweenAsync(const base::Time
& delete_begin
,
263 const base::Time
& delete_end
,
264 const DeleteCallback
& callback
) override
;
266 // Deletes all of the cookies that match the host of the given URL
267 // regardless of path and that have a creation_date greater than or
268 // equal to |delete_begin| and less then |delete_end|. This includes
269 // all http_only and secure cookies, but does not include any domain
270 // cookies that may apply to this host.
271 // Returns the number of cookies deleted.
272 void DeleteAllCreatedBetweenForHostAsync(
273 const base::Time delete_begin
,
274 const base::Time delete_end
,
276 const DeleteCallback
& callback
) override
;
278 void DeleteSessionCookiesAsync(const DeleteCallback
&) override
;
280 CookieMonster
* GetCookieMonster() override
;
282 // Enables writing session cookies into the cookie database. If this this
283 // method is called, it must be called before first use of the instance
284 // (i.e. as part of the instance initialization process).
285 void SetPersistSessionCookies(bool persist_session_cookies
);
287 // Debugging method to perform various validation checks on the map.
288 // Currently just checking that there are no null CanonicalCookie pointers
290 // Argument |arg| is to allow retaining of arbitrary data if the CHECKs
291 // in the function trip. TODO(rdsmith):Remove hack.
292 void ValidateMap(int arg
);
294 // Determines if the scheme of the URL is a scheme that cookies will be
296 bool IsCookieableScheme(const std::string
& scheme
);
298 // The default list of schemes the cookie monster can handle.
299 static const char* const kDefaultCookieableSchemes
[];
300 static const int kDefaultCookieableSchemesCount
;
302 scoped_ptr
<CookieChangedSubscription
> AddCallbackForCookie(
304 const std::string
& name
,
305 const CookieChangedCallback
& callback
) override
;
307 #if defined(OS_ANDROID)
308 // Resets the list of cookieable schemes to kDefaultCookieableSchemes with or
309 // without 'file' being included.
311 // There are some unknowns about how to correctly handle file:// cookies,
312 // and our implementation for this is not robust enough (Bug 1157243).
313 // This allows you to enable support, and is exposed as a public WebView
314 // API ('CookieManager::setAcceptFileSchemeCookies').
316 // TODO(mkwst): This method will be removed once we can deprecate and remove
317 // the Android WebView 'CookieManager::setAcceptFileSchemeCookies' method.
318 // Until then, this method only has effect on Android, and must not be used
319 // outside a WebView context.
320 void SetEnableFileScheme(bool accept
);
324 // For queueing the cookie monster calls.
325 class CookieMonsterTask
;
326 template <typename Result
>
328 class DeleteAllCreatedBetweenTask
;
329 class DeleteAllCreatedBetweenForHostTask
;
330 class DeleteAllForHostTask
;
332 class DeleteCookieTask
;
333 class DeleteCanonicalCookieTask
;
334 class GetAllCookiesForURLWithOptionsTask
;
335 class GetAllCookiesTask
;
336 class GetCookiesWithOptionsTask
;
337 class SetAllCookiesTask
;
338 class SetCookieWithDetailsTask
;
339 class SetCookieWithOptionsTask
;
340 class DeleteSessionCookiesTask
;
341 class HasCookiesForETLDP1Task
;
344 // For SetCookieWithCreationTime.
345 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
,
346 TestCookieDeleteAllCreatedBetweenTimestamps
);
347 // For SetCookieWithCreationTime.
348 FRIEND_TEST_ALL_PREFIXES(MultiThreadedCookieMonsterTest
,
349 ThreadCheckDeleteAllCreatedBetweenForHost
);
351 // For gargage collection constants.
352 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, TestHostGarbageCollection
);
353 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, TestTotalGarbageCollection
);
354 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, GarbageCollectionTriggers
);
355 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, TestGCTimes
);
357 // For validation of key values.
358 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, TestDomainTree
);
359 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, TestImport
);
360 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, GetKey
);
361 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, TestGetKey
);
363 // For FindCookiesForKey.
364 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, ShortLivedSessionCookies
);
366 // For ComputeCookieDiff.
367 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest
, ComputeCookieDiff
);
369 // Internal reasons for deletion, used to populate informative histograms
370 // and to provide a public cause for onCookieChange notifications.
372 // If you add or remove causes from this list, please be sure to also update
373 // the CookieMonsterDelegate::ChangeCause mapping inside ChangeCauseMapping.
374 // Moreover, these are used as array indexes, so avoid reordering to keep the
375 // histogram buckets consistent. New items (if necessary) should be added
376 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
378 DELETE_COOKIE_EXPLICIT
= 0,
379 DELETE_COOKIE_OVERWRITE
,
380 DELETE_COOKIE_EXPIRED
,
381 DELETE_COOKIE_EVICTED
,
382 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
,
383 DELETE_COOKIE_DONT_RECORD
, // e.g. For final cleanup after flush to store.
384 DELETE_COOKIE_EVICTED_DOMAIN
,
385 DELETE_COOKIE_EVICTED_GLOBAL
,
387 // Cookies evicted during domain level garbage collection that
388 // were accessed longer ago than kSafeFromGlobalPurgeDays
389 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
,
391 // Cookies evicted during domain level garbage collection that
392 // were accessed more recently than kSafeFromGlobalPurgeDays
393 // (and thus would have been preserved by global garbage collection).
394 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
,
396 // A common idiom is to remove a cookie by overwriting it with an
397 // already-expired expiration date. This captures that case.
398 DELETE_COOKIE_EXPIRED_OVERWRITE
,
400 // Cookies are not allowed to contain control characters in the name or
401 // value. However, we used to allow them, so we are now evicting any such
402 // cookies as we load them. See http://crbug.com/238041.
403 DELETE_COOKIE_CONTROL_CHAR
,
405 DELETE_COOKIE_LAST_ENTRY
408 // This enum is used to generate a histogramed bitmask measureing the types
409 // of stored cookies. Please do not reorder the list when adding new entries.
410 // New items MUST be added at the end of the list, just before
411 // COOKIE_TYPE_LAST_ENTRY;
413 COOKIE_TYPE_FIRSTPARTYONLY
= 0,
414 COOKIE_TYPE_HTTPONLY
,
416 COOKIE_TYPE_LAST_ENTRY
419 // The number of days since last access that cookies will not be subject
420 // to global garbage collection.
421 static const int kSafeFromGlobalPurgeDays
;
423 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
424 static const int kRecordStatisticsIntervalSeconds
= 10 * 60;
426 ~CookieMonster() override
;
428 // The following are synchronous calls to which the asynchronous methods
429 // delegate either immediately (if the store is loaded) or through a deferred
430 // task (if the store is not yet loaded).
431 bool SetCookieWithDetails(const GURL
& url
,
432 const std::string
& name
,
433 const std::string
& value
,
434 const std::string
& domain
,
435 const std::string
& path
,
436 const base::Time
& expiration_time
,
440 CookiePriority priority
);
442 CookieList
GetAllCookies();
444 CookieList
GetAllCookiesForURLWithOptions(const GURL
& url
,
445 const CookieOptions
& options
);
447 CookieList
GetAllCookiesForURL(const GURL
& url
);
449 int DeleteAll(bool sync_to_store
);
451 int DeleteAllCreatedBetween(const base::Time
& delete_begin
,
452 const base::Time
& delete_end
);
454 int DeleteAllForHost(const GURL
& url
);
455 int DeleteAllCreatedBetweenForHost(const base::Time delete_begin
,
456 const base::Time delete_end
,
459 bool DeleteCanonicalCookie(const CanonicalCookie
& cookie
);
461 bool SetCookieWithOptions(const GURL
& url
,
462 const std::string
& cookie_line
,
463 const CookieOptions
& options
);
465 std::string
GetCookiesWithOptions(const GURL
& url
,
466 const CookieOptions
& options
);
468 void DeleteCookie(const GURL
& url
, const std::string
& cookie_name
);
470 bool SetCookieWithCreationTime(const GURL
& url
,
471 const std::string
& cookie_line
,
472 const base::Time
& creation_time
);
474 int DeleteSessionCookies();
476 bool HasCookiesForETLDP1(const std::string
& etldp1
);
478 // Called by all non-static functions to ensure that the cookies store has
479 // been initialized. This is not done during creating so it doesn't block
480 // the window showing.
481 // Note: this method should always be called with lock_ held.
482 void InitIfNecessary() {
493 // Initializes the backing store and reads existing cookies from it.
494 // Should only be called by InitIfNecessary().
497 // Stores cookies loaded from the backing store and invokes any deferred
498 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
499 // was invoked and is used for reporting histogram_time_blocked_on_load_.
500 // See PersistentCookieStore::Load for details on the contents of cookies.
501 void OnLoaded(base::TimeTicks beginning_time
,
502 const std::vector
<CanonicalCookie
*>& cookies
);
504 // Stores cookies loaded from the backing store and invokes the deferred
505 // task(s) pending loading of cookies associated with the domain key
506 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
507 // loaded from DB. See PersistentCookieStore::Load for details on the contents
509 void OnKeyLoaded(const std::string
& key
,
510 const std::vector
<CanonicalCookie
*>& cookies
);
512 // Stores the loaded cookies.
513 void StoreLoadedCookies(const std::vector
<CanonicalCookie
*>& cookies
);
515 // Invokes deferred calls.
518 // Checks that |cookies_| matches our invariants, and tries to repair any
519 // inconsistencies. (In other words, it does not have duplicate cookies).
520 void EnsureCookiesMapIsValid();
522 // Checks for any duplicate cookies for CookieMap key |key| which lie between
523 // |begin| and |end|. If any are found, all but the most recent are deleted.
524 // Returns the number of duplicate cookies that were deleted.
525 int TrimDuplicateCookiesForKey(const std::string
& key
,
526 CookieMap::iterator begin
,
527 CookieMap::iterator end
);
529 void SetDefaultCookieableSchemes();
531 void FindCookiesForHostAndDomain(const GURL
& url
,
532 const CookieOptions
& options
,
533 bool update_access_time
,
534 std::vector
<CanonicalCookie
*>* cookies
);
536 void FindCookiesForKey(const std::string
& key
,
538 const CookieOptions
& options
,
539 const base::Time
& current
,
540 bool update_access_time
,
541 std::vector
<CanonicalCookie
*>* cookies
);
543 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
544 // If |skip_httponly| is true, httponly cookies will not be deleted. The
545 // return value with be true if |skip_httponly| skipped an httponly cookie.
546 // |key| is the key to find the cookie in cookies_; see the comment before
547 // the CookieMap typedef for details.
548 // NOTE: There should never be more than a single matching equivalent cookie.
549 bool DeleteAnyEquivalentCookie(const std::string
& key
,
550 const CanonicalCookie
& ecc
,
552 bool already_expired
);
554 // Takes ownership of *cc. Returns an iterator that points to the inserted
555 // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
556 CookieMap::iterator
InternalInsertCookie(const std::string
& key
,
560 // Helper function that sets cookies with more control.
561 // Not exposed as we don't want callers to have the ability
562 // to specify (potentially duplicate) creation times.
563 bool SetCookieWithCreationTimeAndOptions(const GURL
& url
,
564 const std::string
& cookie_line
,
565 const base::Time
& creation_time
,
566 const CookieOptions
& options
);
568 // Helper function that sets a canonical cookie, deleting equivalents and
569 // performing garbage collection.
570 bool SetCanonicalCookie(scoped_ptr
<CanonicalCookie
>* cc
,
571 const base::Time
& creation_time
,
572 const CookieOptions
& options
);
574 // Helper function calling SetCanonicalCookie() for all cookies in |list|.
575 bool SetCanonicalCookies(const CookieList
& list
);
577 void InternalUpdateCookieAccessTime(CanonicalCookie
* cc
,
578 const base::Time
& current_time
);
580 // |deletion_cause| argument is used for collecting statistics and choosing
581 // the correct CookieMonsterDelegate::ChangeCause for OnCookieChanged
582 // notifications. Guarantee: All iterators to cookies_ except to the
583 // deleted entry remain vaild.
584 void InternalDeleteCookie(CookieMap::iterator it
,
586 DeletionCause deletion_cause
);
588 // If the number of cookies for CookieMap key |key|, or globally, are
589 // over the preset maximums above, garbage collect, first for the host and
590 // then globally. See comments above garbage collection threshold
591 // constants for details.
593 // Returns the number of cookies deleted (useful for debugging).
594 int GarbageCollect(const base::Time
& current
, const std::string
& key
);
596 // Helper for GarbageCollect(); can be called directly as well. Deletes
597 // all expired cookies in |itpair|. If |cookie_its| is non-NULL, it is
598 // populated with all the non-expired cookies from |itpair|.
600 // Returns the number of cookies deleted.
601 int GarbageCollectExpired(const base::Time
& current
,
602 const CookieMapItPair
& itpair
,
603 std::vector
<CookieMap::iterator
>* cookie_its
);
605 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
606 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
607 int GarbageCollectDeleteRange(const base::Time
& current
,
609 CookieItVector::iterator cookie_its_begin
,
610 CookieItVector::iterator cookie_its_end
);
612 // Find the key (for lookup in cookies_) based on the given domain.
613 // See comment on keys before the CookieMap typedef.
614 std::string
GetKey(const std::string
& domain
) const;
616 bool HasCookieableScheme(const GURL
& url
);
618 // Statistics support
620 // This function should be called repeatedly, and will record
621 // statistics if a sufficient time period has passed.
622 void RecordPeriodicStats(const base::Time
& current_time
);
624 // Initialize the above variables; should only be called from
626 void InitializeHistograms();
628 // The resolution of our time isn't enough, so we do something
629 // ugly and increment when we've seen the same time twice.
630 base::Time
CurrentTime();
632 // Runs the task if, or defers the task until, the full cookie database is
634 void DoCookieTask(const scoped_refptr
<CookieMonsterTask
>& task_item
);
636 // Runs the task if, or defers the task until, the cookies for the given URL
638 void DoCookieTaskForURL(const scoped_refptr
<CookieMonsterTask
>& task_item
,
641 // Computes the difference between |old_cookies| and |new_cookies|, and writes
642 // the result in |cookies_to_add| and |cookies_to_delete|.
643 // This function has the side effect of changing the order of |old_cookies|
644 // and |new_cookies|. |cookies_to_add| and |cookies_to_delete| must be empty,
645 // and none of the arguments can be null.
646 void ComputeCookieDiff(CookieList
* old_cookies
,
647 CookieList
* new_cookies
,
648 CookieList
* cookies_to_add
,
649 CookieList
* cookies_to_delete
);
651 // Run all cookie changed callbacks that are monitoring |cookie|.
652 // |removed| is true if the cookie was deleted.
653 void RunCallbacks(const CanonicalCookie
& cookie
, bool removed
);
655 // Histogram variables; see CookieMonster::InitializeHistograms() in
656 // cookie_monster.cc for details.
657 base::HistogramBase
* histogram_expiration_duration_minutes_
;
658 base::HistogramBase
* histogram_between_access_interval_minutes_
;
659 base::HistogramBase
* histogram_evicted_last_access_minutes_
;
660 base::HistogramBase
* histogram_count_
;
661 base::HistogramBase
* histogram_domain_count_
;
662 base::HistogramBase
* histogram_etldp1_count_
;
663 base::HistogramBase
* histogram_domain_per_etldp1_count_
;
664 base::HistogramBase
* histogram_number_duplicate_db_cookies_
;
665 base::HistogramBase
* histogram_cookie_deletion_cause_
;
666 base::HistogramBase
* histogram_cookie_type_
;
667 base::HistogramBase
* histogram_time_mac_
;
668 base::HistogramBase
* histogram_time_blocked_on_load_
;
672 // Indicates whether the cookie store has been initialized. This happens
673 // lazily in InitStoreIfNecessary().
676 // Indicates whether loading from the backend store is completed and
677 // calls may be immediately processed.
680 // List of domain keys that have been loaded from the DB.
681 std::set
<std::string
> keys_loaded_
;
683 // Map of domain keys to their associated task queues. These tasks are blocked
684 // until all cookies for the associated domain key eTLD+1 are loaded from the
686 std::map
<std::string
, std::deque
<scoped_refptr
<CookieMonsterTask
>>>
687 tasks_pending_for_key_
;
689 // Queues tasks that are blocked until all cookies are loaded from the backend
691 std::queue
<scoped_refptr
<CookieMonsterTask
>> tasks_pending_
;
693 scoped_refptr
<PersistentCookieStore
> store_
;
695 base::Time last_time_seen_
;
697 // Minimum delay after updating a cookie's LastAccessDate before we will
699 const base::TimeDelta last_access_threshold_
;
701 // Approximate date of access time of least recently accessed cookie
702 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
703 // to be before or equal to the actual time, and b) to be accurate
704 // immediately after a garbage collection that scans through all the cookies.
705 // This value is used to determine whether global garbage collection might
706 // find cookies to purge.
707 // Note: The default Time() constructor will create a value that compares
708 // earlier than any other time value, which is wanted. Thus this
709 // value is not initialized.
710 base::Time earliest_access_time_
;
712 // During loading, holds the set of all loaded cookie creation times. Used to
713 // avoid ever letting cookies with duplicate creation times into the store;
714 // that way we don't have to worry about what sections of code are safe
715 // to call while it's in that state.
716 std::set
<int64
> creation_times_
;
718 std::vector
<std::string
> cookieable_schemes_
;
720 scoped_refptr
<CookieMonsterDelegate
> delegate_
;
722 // Lock for thread-safety
725 base::Time last_statistic_record_time_
;
727 bool keep_expired_cookies_
;
728 bool persist_session_cookies_
;
730 // Static setting for whether or not file scheme cookies are allows when
731 // a new CookieMonster is created, or the accepted schemes on a CookieMonster
732 // instance are reset back to defaults.
733 static bool default_enable_file_scheme_
;
735 typedef std::map
<std::pair
<GURL
, std::string
>,
736 linked_ptr
<CookieChangedCallbackList
>> CookieChangedHookMap
;
737 CookieChangedHookMap hook_map_
;
739 DISALLOW_COPY_AND_ASSIGN(CookieMonster
);
742 class NET_EXPORT CookieMonsterDelegate
743 : public base::RefCountedThreadSafe
<CookieMonsterDelegate
> {
745 // The publicly relevant reasons a cookie might be changed.
747 // The cookie was changed directly by a consumer's action.
748 CHANGE_COOKIE_EXPLICIT
,
749 // The cookie was automatically removed due to an insert operation that
751 CHANGE_COOKIE_OVERWRITE
,
752 // The cookie was automatically removed as it expired.
753 CHANGE_COOKIE_EXPIRED
,
754 // The cookie was automatically evicted during garbage collection.
755 CHANGE_COOKIE_EVICTED
,
756 // The cookie was overwritten with an already-expired expiration date.
757 CHANGE_COOKIE_EXPIRED_OVERWRITE
760 // Will be called when a cookie is added or removed. The function is passed
761 // the respective |cookie| which was added to or removed from the cookies.
762 // If |removed| is true, the cookie was deleted, and |cause| will be set
763 // to the reason for its removal. If |removed| is false, the cookie was
764 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
766 // As a special case, note that updating a cookie's properties is implemented
767 // as a two step process: the cookie to be updated is first removed entirely,
768 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
769 // a new cookie is written with the updated values, generating a notification
770 // with cause CHANGE_COOKIE_EXPLICIT.
771 virtual void OnCookieChanged(const CanonicalCookie
& cookie
,
773 ChangeCause cause
) = 0;
775 friend class base::RefCountedThreadSafe
<CookieMonsterDelegate
>;
776 virtual ~CookieMonsterDelegate() {}
779 typedef base::RefCountedThreadSafe
<CookieMonster::PersistentCookieStore
>
780 RefcountedPersistentCookieStore
;
782 class NET_EXPORT
CookieMonster::PersistentCookieStore
783 : public RefcountedPersistentCookieStore
{
785 typedef base::Callback
<void(const std::vector
<CanonicalCookie
*>&)>
788 // Initializes the store and retrieves the existing cookies. This will be
789 // called only once at startup. The callback will return all the cookies
790 // that are not yet returned to CookieMonster by previous priority loads.
791 virtual void Load(const LoadedCallback
& loaded_callback
) = 0;
793 // Does a priority load of all cookies for the domain key (eTLD+1). The
794 // callback will return all the cookies that are not yet returned by previous
795 // loads, which includes cookies for the requested domain key if they are not
796 // already returned, plus all cookies that are chain-loaded and not yet
797 // returned to CookieMonster.
798 virtual void LoadCookiesForKey(const std::string
& key
,
799 const LoadedCallback
& loaded_callback
) = 0;
801 virtual void AddCookie(const CanonicalCookie
& cc
) = 0;
802 virtual void UpdateCookieAccessTime(const CanonicalCookie
& cc
) = 0;
803 virtual void DeleteCookie(const CanonicalCookie
& cc
) = 0;
805 // Instructs the store to not discard session only cookies on shutdown.
806 virtual void SetForceKeepSessionState() = 0;
808 // Flushes the store and posts |callback| when complete.
809 virtual void Flush(const base::Closure
& callback
) = 0;
812 PersistentCookieStore() {}
813 virtual ~PersistentCookieStore() {}
816 friend class base::RefCountedThreadSafe
<PersistentCookieStore
>;
817 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore
);
822 #endif // NET_COOKIES_COOKIE_MONSTER_H_