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/ref_counted.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/synchronization/lock.h"
24 #include "base/time/time.h"
25 #include "net/base/net_export.h"
26 #include "net/cookies/canonical_cookie.h"
27 #include "net/cookies/cookie_constants.h"
28 #include "net/cookies/cookie_store.h"
42 // The cookie monster is the system for storing and retrieving cookies. It has
43 // an in-memory list of all cookies, and synchronizes non-session cookies to an
44 // optional permanent storage that implements the PersistentCookieStore
47 // This class IS thread-safe. Normally, it is only used on the I/O thread, but
48 // is also accessed directly through Automation for UI testing.
50 // All cookie tasks are handled asynchronously. Tasks may be deferred if
51 // all affected cookies are not yet loaded from the backing store. Otherwise,
52 // the callback may be invoked immediately (prior to return of the asynchronous
55 // A cookie task is either pending loading of the entire cookie store, or
56 // loading of cookies for a specfic domain key(eTLD+1). In the former case, the
57 // cookie task will be queued in tasks_pending_ while PersistentCookieStore
58 // chain loads the cookie store on DB thread. In the latter case, the cookie
59 // task will be queued in tasks_pending_for_key_ while PermanentCookieStore
60 // loads cookies for the specified domain key(eTLD+1) on DB thread.
62 // Callbacks are guaranteed to be invoked on the calling thread.
64 // TODO(deanm) Implement CookieMonster, the cookie database.
65 // - Verify that our domain enforcement and non-dotted handling is correct
66 class NET_EXPORT CookieMonster : public CookieStore {
69 class PersistentCookieStore;
72 // * The 'top level domain' (TLD) of an internet domain name is
73 // the terminal "." free substring (e.g. "com" for google.com
75 // * The 'effective top level domain' (eTLD) is the longest
76 // "." initiated terminal substring of an internet domain name
77 // that is controlled by a general domain registrar.
78 // (e.g. "co.uk" for news.bbc.co.uk).
79 // * The 'effective top level domain plus one' (eTLD+1) is the
80 // shortest "." delimited terminal substring of an internet
81 // domain name that is not controlled by a general domain
82 // registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
83 // "google.com" for news.google.com). The general assumption
84 // is that all hosts and domains under an eTLD+1 share some
85 // administrative control.
87 // CookieMap is the central data structure of the CookieMonster. It
88 // is a map whose values are pointers to CanonicalCookie data
89 // structures (the data structures are owned by the CookieMonster
90 // and must be destroyed when removed from the map). The key is based on the
91 // effective domain of the cookies. If the domain of the cookie has an
92 // eTLD+1, that is the key for the map. If the domain of the cookie does not
93 // have an eTLD+1, the key of the map is the host the cookie applies to (it is
94 // not legal to have domain cookies without an eTLD+1). This rule
95 // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
96 // This behavior is the same as the behavior in Firefox v 3.6.10.
99 // I benchmarked hash_multimap vs multimap. We're going to be query-heavy
100 // so it would seem like hashing would help. However they were very
101 // close, with multimap being a tiny bit faster. I think this is because
102 // our map is at max around 1000 entries, and the additional complexity
103 // for the hashing might not overcome the O(log(1000)) for querying
104 // a multimap. Also, multimap is standard, another reason to use it.
105 // TODO(rdsmith): This benchmark should be re-done now that we're allowing
106 // subtantially more entries in the map.
107 typedef std::multimap<std::string, CanonicalCookie*> CookieMap;
108 typedef std::pair<CookieMap::iterator, CookieMap::iterator> CookieMapItPair;
109 typedef std::vector<CookieMap::iterator> CookieItVector;
111 // Cookie garbage collection thresholds. Based off of the Mozilla defaults.
112 // When the number of cookies gets to k{Domain,}MaxCookies
113 // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
114 // It might seem scary to have a high purge value, but really it's not.
115 // You just make sure that you increase the max to cover the increase
116 // in purge, and we would have been purging the same number of cookies.
117 // We're just going through the garbage collection process less often.
118 // Note that the DOMAIN values are per eTLD+1; see comment for the
119 // CookieMap typedef. So, e.g., the maximum number of cookies allowed for
120 // google.com and all of its subdomains will be 150-180.
122 // Any cookies accessed more recently than kSafeFromGlobalPurgeDays will not
123 // be evicted by global garbage collection, even if we have more than
124 // kMaxCookies. This does not affect domain garbage collection.
125 static const size_t kDomainMaxCookies;
126 static const size_t kDomainPurgeCookies;
127 static const size_t kMaxCookies;
128 static const size_t kPurgeCookies;
130 // Quota for cookies with {low, medium, high} priorities within a domain.
131 static const size_t kDomainCookiesQuotaLow;
132 static const size_t kDomainCookiesQuotaMedium;
133 static const size_t kDomainCookiesQuotaHigh;
135 // The store passed in should not have had Init() called on it yet. This
136 // class will take care of initializing it. The backing store is NOT owned by
137 // this class, but it must remain valid for the duration of the cookie
138 // monster's existence. If |store| is NULL, then no backing store will be
139 // updated. If |delegate| is non-NULL, it will be notified on
140 // creation/deletion of cookies.
141 CookieMonster(PersistentCookieStore* store, Delegate* delegate);
143 // Only used during unit testing.
144 CookieMonster(PersistentCookieStore* store,
146 int last_access_threshold_milliseconds);
148 // Helper function that adds all cookies from |list| into this instance.
149 bool InitializeFrom(const CookieList& list);
151 typedef base::Callback<void(const CookieList& cookies)> GetCookieListCallback;
152 typedef base::Callback<void(bool success)> DeleteCookieCallback;
153 typedef base::Callback<void(bool cookies_exist)> HasCookiesForETLDP1Callback;
155 // Sets a cookie given explicit user-provided cookie attributes. The cookie
156 // name, value, domain, etc. are each provided as separate strings. This
157 // function expects each attribute to be well-formed. It will check for
158 // disallowed characters (e.g. the ';' character is disallowed within the
159 // cookie value attribute) and will return false without setting the cookie
160 // if such characters are found.
161 void SetCookieWithDetailsAsync(const GURL& url,
162 const std::string& name,
163 const std::string& value,
164 const std::string& domain,
165 const std::string& path,
166 const base::Time& expiration_time,
169 CookiePriority priority,
170 const SetCookiesCallback& callback);
173 // Returns all the cookies, for use in management UI, etc. This does not mark
174 // the cookies as having been accessed.
175 // The returned cookies are ordered by longest path, then by earliest
177 void GetAllCookiesAsync(const GetCookieListCallback& callback);
179 // Returns all the cookies, for use in management UI, etc. Filters results
180 // using given url scheme, host / domain and path and options. This does not
181 // mark the cookies as having been accessed.
182 // The returned cookies are ordered by longest path, then earliest
184 void GetAllCookiesForURLWithOptionsAsync(
186 const CookieOptions& options,
187 const GetCookieListCallback& callback);
189 // Invokes GetAllCookiesForURLWithOptions with options set to include HTTP
191 void GetAllCookiesForURLAsync(const GURL& url,
192 const GetCookieListCallback& callback);
194 // Deletes all of the cookies.
195 void DeleteAllAsync(const DeleteCallback& callback);
197 // Deletes all cookies that match the host of the given URL
198 // regardless of path. This includes all http_only and secure cookies,
199 // but does not include any domain cookies that may apply to this host.
200 // Returns the number of cookies deleted.
201 void DeleteAllForHostAsync(const GURL& url,
202 const DeleteCallback& callback);
204 // Same as DeleteAllForHostAsync, except it deletes cookies between
205 // [|delete_begin|, |delete_end|).
206 // Returns the number of cookies deleted.
207 void DeleteAllCreatedBetweenForHostAsync(const base::Time delete_begin,
208 const base::Time delete_end,
210 const DeleteCallback& callback);
212 // Deletes one specific cookie.
213 void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
214 const DeleteCookieCallback& callback);
216 // Checks whether for a given ETLD+1, there currently exist any cookies.
217 void HasCookiesForETLDP1Async(const std::string& etldp1,
218 const HasCookiesForETLDP1Callback& callback);
220 // Resets the list of cookieable schemes to the supplied schemes.
221 // If this this method is called, it must be called before first use of
222 // the instance (i.e. as part of the instance initialization process).
223 void SetCookieableSchemes(const char* schemes[], size_t num_schemes);
225 // Resets the list of cookieable schemes to kDefaultCookieableSchemes with or
226 // without 'file' being included.
227 void SetEnableFileScheme(bool accept);
229 // Instructs the cookie monster to not delete expired cookies. This is used
230 // in cases where the cookie monster is used as a data structure to keep
231 // arbitrary cookies.
232 void SetKeepExpiredCookies();
234 // Protects session cookies from deletion on shutdown.
235 void SetForceKeepSessionState();
237 // There are some unknowns about how to correctly handle file:// cookies,
238 // and our implementation for this is not robust enough. This allows you
239 // to enable support, but it should only be used for testing. Bug 1157243.
240 // Must be called before creating a CookieMonster instance.
241 static void EnableFileScheme();
243 // Flush the backing store (if any) to disk and post the given callback when
245 // WARNING: THE CALLBACK WILL RUN ON A RANDOM THREAD. IT MUST BE THREAD SAFE.
246 // It may be posted to the current thread, or it may run on the thread that
247 // actually does the flushing. Your Task should generally post a notification
248 // to the thread you actually want to be notified on.
249 void FlushStore(const base::Closure& callback);
251 // CookieStore implementation.
253 // Sets the cookies specified by |cookie_list| returned from |url|
254 // with options |options| in effect.
255 virtual void SetCookieWithOptionsAsync(
257 const std::string& cookie_line,
258 const CookieOptions& options,
259 const SetCookiesCallback& callback) OVERRIDE;
261 // Gets all cookies that apply to |url| given |options|.
262 // The returned cookies are ordered by longest path, then earliest
264 virtual void GetCookiesWithOptionsAsync(
266 const CookieOptions& options,
267 const GetCookiesCallback& callback) OVERRIDE;
269 // Deletes all cookies with that might apply to |url| that has |cookie_name|.
270 virtual void DeleteCookieAsync(
271 const GURL& url, const std::string& cookie_name,
272 const base::Closure& callback) OVERRIDE;
274 // Deletes all of the cookies that have a creation_date greater than or equal
275 // to |delete_begin| and less than |delete_end|
276 // Returns the number of cookies that have been deleted.
277 virtual void DeleteAllCreatedBetweenAsync(
278 const base::Time& delete_begin,
279 const base::Time& delete_end,
280 const DeleteCallback& callback) OVERRIDE;
282 virtual void DeleteSessionCookiesAsync(const DeleteCallback&) OVERRIDE;
284 virtual CookieMonster* GetCookieMonster() OVERRIDE;
286 // Enables writing session cookies into the cookie database. If this this
287 // method is called, it must be called before first use of the instance
288 // (i.e. as part of the instance initialization process).
289 void SetPersistSessionCookies(bool persist_session_cookies);
291 // Debugging method to perform various validation checks on the map.
292 // Currently just checking that there are no null CanonicalCookie pointers
294 // Argument |arg| is to allow retaining of arbitrary data if the CHECKs
295 // in the function trip. TODO(rdsmith):Remove hack.
296 void ValidateMap(int arg);
298 // Determines if the scheme of the URL is a scheme that cookies will be
300 bool IsCookieableScheme(const std::string& scheme);
302 // The default list of schemes the cookie monster can handle.
303 static const char* kDefaultCookieableSchemes[];
304 static const int kDefaultCookieableSchemesCount;
307 // For queueing the cookie monster calls.
308 class CookieMonsterTask;
309 template <typename Result> class DeleteTask;
310 class DeleteAllCreatedBetweenTask;
311 class DeleteAllCreatedBetweenForHostTask;
312 class DeleteAllForHostTask;
314 class DeleteCookieTask;
315 class DeleteCanonicalCookieTask;
316 class GetAllCookiesForURLWithOptionsTask;
317 class GetAllCookiesTask;
318 class GetCookiesWithOptionsTask;
319 class SetCookieWithDetailsTask;
320 class SetCookieWithOptionsTask;
321 class DeleteSessionCookiesTask;
322 class HasCookiesForETLDP1Task;
325 // For SetCookieWithCreationTime.
326 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
327 TestCookieDeleteAllCreatedBetweenTimestamps);
328 // For SetCookieWithCreationTime.
329 FRIEND_TEST_ALL_PREFIXES(MultiThreadedCookieMonsterTest,
330 ThreadCheckDeleteAllCreatedBetweenForHost);
332 // For gargage collection constants.
333 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
334 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
335 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
336 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
338 // For validation of key values.
339 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
340 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
341 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
342 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
344 // For FindCookiesForKey.
345 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
347 // Internal reasons for deletion, used to populate informative histograms
348 // and to provide a public cause for onCookieChange notifications.
350 // If you add or remove causes from this list, please be sure to also update
351 // the Delegate::ChangeCause mapping inside ChangeCauseMapping. Moreover,
352 // these are used as array indexes, so avoid reordering to keep the
353 // histogram buckets consistent. New items (if necessary) should be added
354 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
356 DELETE_COOKIE_EXPLICIT = 0,
357 DELETE_COOKIE_OVERWRITE,
358 DELETE_COOKIE_EXPIRED,
359 DELETE_COOKIE_EVICTED,
360 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
361 DELETE_COOKIE_DONT_RECORD, // e.g. For final cleanup after flush to store.
362 DELETE_COOKIE_EVICTED_DOMAIN,
363 DELETE_COOKIE_EVICTED_GLOBAL,
365 // Cookies evicted during domain level garbage collection that
366 // were accessed longer ago than kSafeFromGlobalPurgeDays
367 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
369 // Cookies evicted during domain level garbage collection that
370 // were accessed more recently than kSafeFromGlobalPurgeDays
371 // (and thus would have been preserved by global garbage collection).
372 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
374 // A common idiom is to remove a cookie by overwriting it with an
375 // already-expired expiration date. This captures that case.
376 DELETE_COOKIE_EXPIRED_OVERWRITE,
378 // Cookies are not allowed to contain control characters in the name or
379 // value. However, we used to allow them, so we are now evicting any such
380 // cookies as we load them. See http://crbug.com/238041.
381 DELETE_COOKIE_CONTROL_CHAR,
383 DELETE_COOKIE_LAST_ENTRY
386 // The number of days since last access that cookies will not be subject
387 // to global garbage collection.
388 static const int kSafeFromGlobalPurgeDays;
390 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
391 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
393 virtual ~CookieMonster();
395 // The following are synchronous calls to which the asynchronous methods
396 // delegate either immediately (if the store is loaded) or through a deferred
397 // task (if the store is not yet loaded).
398 bool SetCookieWithDetails(const GURL& url,
399 const std::string& name,
400 const std::string& value,
401 const std::string& domain,
402 const std::string& path,
403 const base::Time& expiration_time,
406 CookiePriority priority);
408 CookieList GetAllCookies();
410 CookieList GetAllCookiesForURLWithOptions(const GURL& url,
411 const CookieOptions& options);
413 CookieList GetAllCookiesForURL(const GURL& url);
415 int DeleteAll(bool sync_to_store);
417 int DeleteAllCreatedBetween(const base::Time& delete_begin,
418 const base::Time& delete_end);
420 int DeleteAllForHost(const GURL& url);
421 int DeleteAllCreatedBetweenForHost(const base::Time delete_begin,
422 const base::Time delete_end,
425 bool DeleteCanonicalCookie(const CanonicalCookie& cookie);
427 bool SetCookieWithOptions(const GURL& url,
428 const std::string& cookie_line,
429 const CookieOptions& options);
431 std::string GetCookiesWithOptions(const GURL& url,
432 const CookieOptions& options);
434 void DeleteCookie(const GURL& url, const std::string& cookie_name);
436 bool SetCookieWithCreationTime(const GURL& url,
437 const std::string& cookie_line,
438 const base::Time& creation_time);
440 int DeleteSessionCookies();
442 bool HasCookiesForETLDP1(const std::string& etldp1);
444 // Called by all non-static functions to ensure that the cookies store has
445 // been initialized. This is not done during creating so it doesn't block
446 // the window showing.
447 // Note: this method should always be called with lock_ held.
448 void InitIfNecessary() {
459 // Initializes the backing store and reads existing cookies from it.
460 // Should only be called by InitIfNecessary().
463 // Stores cookies loaded from the backing store and invokes any deferred
464 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
465 // was invoked and is used for reporting histogram_time_blocked_on_load_.
466 // See PersistentCookieStore::Load for details on the contents of cookies.
467 void OnLoaded(base::TimeTicks beginning_time,
468 const std::vector<CanonicalCookie*>& cookies);
470 // Stores cookies loaded from the backing store and invokes the deferred
471 // task(s) pending loading of cookies associated with the domain key
472 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
473 // loaded from DB. See PersistentCookieStore::Load for details on the contents
476 const std::string& key,
477 const std::vector<CanonicalCookie*>& cookies);
479 // Stores the loaded cookies.
480 void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);
482 // Invokes deferred calls.
485 // Checks that |cookies_| matches our invariants, and tries to repair any
486 // inconsistencies. (In other words, it does not have duplicate cookies).
487 void EnsureCookiesMapIsValid();
489 // Checks for any duplicate cookies for CookieMap key |key| which lie between
490 // |begin| and |end|. If any are found, all but the most recent are deleted.
491 // Returns the number of duplicate cookies that were deleted.
492 int TrimDuplicateCookiesForKey(const std::string& key,
493 CookieMap::iterator begin,
494 CookieMap::iterator end);
496 void SetDefaultCookieableSchemes();
498 void FindCookiesForHostAndDomain(const GURL& url,
499 const CookieOptions& options,
500 bool update_access_time,
501 std::vector<CanonicalCookie*>* cookies);
503 void FindCookiesForKey(const std::string& key,
505 const CookieOptions& options,
506 const base::Time& current,
507 bool update_access_time,
508 std::vector<CanonicalCookie*>* cookies);
510 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
511 // If |skip_httponly| is true, httponly cookies will not be deleted. The
512 // return value with be true if |skip_httponly| skipped an httponly cookie.
513 // |key| is the key to find the cookie in cookies_; see the comment before
514 // the CookieMap typedef for details.
515 // NOTE: There should never be more than a single matching equivalent cookie.
516 bool DeleteAnyEquivalentCookie(const std::string& key,
517 const CanonicalCookie& ecc,
519 bool already_expired);
521 // Takes ownership of *cc. Returns an iterator that points to the inserted
522 // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
523 CookieMap::iterator InternalInsertCookie(const std::string& key,
527 // Helper function that sets cookies with more control.
528 // Not exposed as we don't want callers to have the ability
529 // to specify (potentially duplicate) creation times.
530 bool SetCookieWithCreationTimeAndOptions(const GURL& url,
531 const std::string& cookie_line,
532 const base::Time& creation_time,
533 const CookieOptions& options);
535 // Helper function that sets a canonical cookie, deleting equivalents and
536 // performing garbage collection.
537 bool SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
538 const base::Time& creation_time,
539 const CookieOptions& options);
541 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
542 const base::Time& current_time);
544 // |deletion_cause| argument is used for collecting statistics and choosing
545 // the correct Delegate::ChangeCause for OnCookieChanged notifications.
546 // Guarantee: All iterators to cookies_ except to the deleted entry remain
548 void InternalDeleteCookie(CookieMap::iterator it, bool sync_to_store,
549 DeletionCause deletion_cause);
551 // If the number of cookies for CookieMap key |key|, or globally, are
552 // over the preset maximums above, garbage collect, first for the host and
553 // then globally. See comments above garbage collection threshold
554 // constants for details.
556 // Returns the number of cookies deleted (useful for debugging).
557 int GarbageCollect(const base::Time& current, const std::string& key);
559 // Helper for GarbageCollect(); can be called directly as well. Deletes
560 // all expired cookies in |itpair|. If |cookie_its| is non-NULL, it is
561 // populated with all the non-expired cookies from |itpair|.
563 // Returns the number of cookies deleted.
564 int GarbageCollectExpired(const base::Time& current,
565 const CookieMapItPair& itpair,
566 std::vector<CookieMap::iterator>* cookie_its);
568 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
569 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
570 int GarbageCollectDeleteRange(const base::Time& current,
572 CookieItVector::iterator cookie_its_begin,
573 CookieItVector::iterator cookie_its_end);
575 // Find the key (for lookup in cookies_) based on the given domain.
576 // See comment on keys before the CookieMap typedef.
577 std::string GetKey(const std::string& domain) const;
579 bool HasCookieableScheme(const GURL& url);
581 // Statistics support
583 // This function should be called repeatedly, and will record
584 // statistics if a sufficient time period has passed.
585 void RecordPeriodicStats(const base::Time& current_time);
587 // Initialize the above variables; should only be called from
589 void InitializeHistograms();
591 // The resolution of our time isn't enough, so we do something
592 // ugly and increment when we've seen the same time twice.
593 base::Time CurrentTime();
595 // Runs the task if, or defers the task until, the full cookie database is
597 void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);
599 // Runs the task if, or defers the task until, the cookies for the given URL
601 void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
604 // Histogram variables; see CookieMonster::InitializeHistograms() in
605 // cookie_monster.cc for details.
606 base::HistogramBase* histogram_expiration_duration_minutes_;
607 base::HistogramBase* histogram_between_access_interval_minutes_;
608 base::HistogramBase* histogram_evicted_last_access_minutes_;
609 base::HistogramBase* histogram_count_;
610 base::HistogramBase* histogram_domain_count_;
611 base::HistogramBase* histogram_etldp1_count_;
612 base::HistogramBase* histogram_domain_per_etldp1_count_;
613 base::HistogramBase* histogram_number_duplicate_db_cookies_;
614 base::HistogramBase* histogram_cookie_deletion_cause_;
615 base::HistogramBase* histogram_time_get_;
616 base::HistogramBase* histogram_time_mac_;
617 base::HistogramBase* histogram_time_blocked_on_load_;
621 // Indicates whether the cookie store has been initialized. This happens
622 // lazily in InitStoreIfNecessary().
625 // Indicates whether loading from the backend store is completed and
626 // calls may be immediately processed.
629 // List of domain keys that have been loaded from the DB.
630 std::set<std::string> keys_loaded_;
632 // Map of domain keys to their associated task queues. These tasks are blocked
633 // until all cookies for the associated domain key eTLD+1 are loaded from the
635 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask> > >
636 tasks_pending_for_key_;
638 // Queues tasks that are blocked until all cookies are loaded from the backend
640 std::queue<scoped_refptr<CookieMonsterTask> > tasks_pending_;
642 scoped_refptr<PersistentCookieStore> store_;
644 base::Time last_time_seen_;
646 // Minimum delay after updating a cookie's LastAccessDate before we will
648 const base::TimeDelta last_access_threshold_;
650 // Approximate date of access time of least recently accessed cookie
651 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
652 // to be before or equal to the actual time, and b) to be accurate
653 // immediately after a garbage collection that scans through all the cookies.
654 // This value is used to determine whether global garbage collection might
655 // find cookies to purge.
656 // Note: The default Time() constructor will create a value that compares
657 // earlier than any other time value, which is wanted. Thus this
658 // value is not initialized.
659 base::Time earliest_access_time_;
661 // During loading, holds the set of all loaded cookie creation times. Used to
662 // avoid ever letting cookies with duplicate creation times into the store;
663 // that way we don't have to worry about what sections of code are safe
664 // to call while it's in that state.
665 std::set<int64> creation_times_;
667 std::vector<std::string> cookieable_schemes_;
669 scoped_refptr<Delegate> delegate_;
671 // Lock for thread-safety
674 base::Time last_statistic_record_time_;
676 bool keep_expired_cookies_;
677 bool persist_session_cookies_;
679 // Static setting for whether or not file scheme cookies are allows when
680 // a new CookieMonster is created, or the accepted schemes on a CookieMonster
681 // instance are reset back to defaults.
682 static bool default_enable_file_scheme_;
684 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
687 class NET_EXPORT CookieMonster::Delegate
688 : public base::RefCountedThreadSafe<CookieMonster::Delegate> {
690 // The publicly relevant reasons a cookie might be changed.
692 // The cookie was changed directly by a consumer's action.
693 CHANGE_COOKIE_EXPLICIT,
694 // The cookie was automatically removed due to an insert operation that
696 CHANGE_COOKIE_OVERWRITE,
697 // The cookie was automatically removed as it expired.
698 CHANGE_COOKIE_EXPIRED,
699 // The cookie was automatically evicted during garbage collection.
700 CHANGE_COOKIE_EVICTED,
701 // The cookie was overwritten with an already-expired expiration date.
702 CHANGE_COOKIE_EXPIRED_OVERWRITE
705 // Will be called when a cookie is added or removed. The function is passed
706 // the respective |cookie| which was added to or removed from the cookies.
707 // If |removed| is true, the cookie was deleted, and |cause| will be set
708 // to the reason for its removal. If |removed| is false, the cookie was
709 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
711 // As a special case, note that updating a cookie's properties is implemented
712 // as a two step process: the cookie to be updated is first removed entirely,
713 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
714 // a new cookie is written with the updated values, generating a notification
715 // with cause CHANGE_COOKIE_EXPLICIT.
716 virtual void OnCookieChanged(const CanonicalCookie& cookie,
718 ChangeCause cause) = 0;
720 friend class base::RefCountedThreadSafe<CookieMonster::Delegate>;
721 virtual ~Delegate() {}
724 typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
725 RefcountedPersistentCookieStore;
727 class NET_EXPORT CookieMonster::PersistentCookieStore
728 : public RefcountedPersistentCookieStore {
730 typedef base::Callback<void(const std::vector<CanonicalCookie*>&)>
733 // Initializes the store and retrieves the existing cookies. This will be
734 // called only once at startup. The callback will return all the cookies
735 // that are not yet returned to CookieMonster by previous priority loads.
736 virtual void Load(const LoadedCallback& loaded_callback) = 0;
738 // Does a priority load of all cookies for the domain key (eTLD+1). The
739 // callback will return all the cookies that are not yet returned by previous
740 // loads, which includes cookies for the requested domain key if they are not
741 // already returned, plus all cookies that are chain-loaded and not yet
742 // returned to CookieMonster.
743 virtual void LoadCookiesForKey(const std::string& key,
744 const LoadedCallback& loaded_callback) = 0;
746 virtual void AddCookie(const CanonicalCookie& cc) = 0;
747 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
748 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
750 // Instructs the store to not discard session only cookies on shutdown.
751 virtual void SetForceKeepSessionState() = 0;
753 // Flushes the store and posts |callback| when complete.
754 virtual void Flush(const base::Closure& callback) = 0;
757 PersistentCookieStore() {}
758 virtual ~PersistentCookieStore() {}
761 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
762 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
767 #endif // NET_COOKIES_COOKIE_MONSTER_H_