Port Android relocation packer to chromium build
[chromium-blink-merge.git] / net / cookies / cookie_monster.h
blob5633baf2679c490d5ea0f639cf46d908e291c0f0
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_
10 #include <deque>
11 #include <map>
12 #include <queue>
13 #include <set>
14 #include <string>
15 #include <utility>
16 #include <vector>
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"
30 #include "url/gurl.h"
32 namespace base {
33 class Histogram;
34 class HistogramBase;
35 class TimeTicks;
36 } // namespace base
38 namespace net {
40 class CookieMonsterDelegate;
41 class ParsedCookie;
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
46 // interface.
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
54 // function).
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 {
68 public:
69 class PersistentCookieStore;
70 typedef CookieMonsterDelegate Delegate;
72 // Terminology:
73 // * The 'top level domain' (TLD) of an internet domain name is
74 // the terminal "." free substring (e.g. "com" for google.com
75 // or world.std.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.
99 // NOTE(deanm):
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,
169 bool secure,
170 bool http_only,
171 bool first_party,
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
178 // creation date.
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
185 // creation date.
186 void GetAllCookiesForURLWithOptionsAsync(
187 const GURL& url,
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 // Resets the list of cookieable schemes to kDefaultCookieableSchemes with or
214 // without 'file' being included.
216 // There are some unknowns about how to correctly handle file:// cookies,
217 // and our implementation for this is not robust enough. This allows you
218 // to enable support, but it should only be used for testing. Bug 1157243.
219 void SetEnableFileScheme(bool accept);
221 // Instructs the cookie monster to not delete expired cookies. This is used
222 // in cases where the cookie monster is used as a data structure to keep
223 // arbitrary cookies.
224 void SetKeepExpiredCookies();
226 // Protects session cookies from deletion on shutdown.
227 void SetForceKeepSessionState();
229 // Flush the backing store (if any) to disk and post the given callback when
230 // done.
231 // WARNING: THE CALLBACK WILL RUN ON A RANDOM THREAD. IT MUST BE THREAD SAFE.
232 // It may be posted to the current thread, or it may run on the thread that
233 // actually does the flushing. Your Task should generally post a notification
234 // to the thread you actually want to be notified on.
235 void FlushStore(const base::Closure& callback);
237 // Replaces all the cookies by |list|. This method does not flush the backend.
238 void SetAllCookiesAsync(const CookieList& list,
239 const SetCookiesCallback& callback);
241 // CookieStore implementation.
243 // Sets the cookies specified by |cookie_list| returned from |url|
244 // with options |options| in effect.
245 void SetCookieWithOptionsAsync(const GURL& url,
246 const std::string& cookie_line,
247 const CookieOptions& options,
248 const SetCookiesCallback& callback) override;
250 // Gets all cookies that apply to |url| given |options|.
251 // The returned cookies are ordered by longest path, then earliest
252 // creation date.
253 void GetCookiesWithOptionsAsync(const GURL& url,
254 const CookieOptions& options,
255 const GetCookiesCallback& callback) override;
257 // Invokes GetAllCookiesForURLWithOptions with options set to include HTTP
258 // only cookies.
259 void GetAllCookiesForURLAsync(const GURL& url,
260 const GetCookieListCallback& callback) override;
262 // Deletes all cookies with that might apply to |url| that has |cookie_name|.
263 void DeleteCookieAsync(const GURL& url,
264 const std::string& cookie_name,
265 const base::Closure& callback) override;
267 // Deletes all of the cookies that have a creation_date greater than or equal
268 // to |delete_begin| and less than |delete_end|.
269 // Returns the number of cookies that have been deleted.
270 void DeleteAllCreatedBetweenAsync(const base::Time& delete_begin,
271 const base::Time& delete_end,
272 const DeleteCallback& callback) override;
274 // Deletes all of the cookies that match the host of the given URL
275 // regardless of path and that have a creation_date greater than or
276 // equal to |delete_begin| and less then |delete_end|. This includes
277 // all http_only and secure cookies, but does not include any domain
278 // cookies that may apply to this host.
279 // Returns the number of cookies deleted.
280 void DeleteAllCreatedBetweenForHostAsync(
281 const base::Time delete_begin,
282 const base::Time delete_end,
283 const GURL& url,
284 const DeleteCallback& callback) override;
286 void DeleteSessionCookiesAsync(const DeleteCallback&) override;
288 CookieMonster* GetCookieMonster() override;
290 // Enables writing session cookies into the cookie database. If this this
291 // method is called, it must be called before first use of the instance
292 // (i.e. as part of the instance initialization process).
293 void SetPersistSessionCookies(bool persist_session_cookies);
295 // Debugging method to perform various validation checks on the map.
296 // Currently just checking that there are no null CanonicalCookie pointers
297 // in the map.
298 // Argument |arg| is to allow retaining of arbitrary data if the CHECKs
299 // in the function trip. TODO(rdsmith):Remove hack.
300 void ValidateMap(int arg);
302 // Determines if the scheme of the URL is a scheme that cookies will be
303 // stored for.
304 bool IsCookieableScheme(const std::string& scheme);
306 // The default list of schemes the cookie monster can handle.
307 static const char* const kDefaultCookieableSchemes[];
308 static const int kDefaultCookieableSchemesCount;
310 scoped_ptr<CookieChangedSubscription> AddCallbackForCookie(
311 const GURL& url,
312 const std::string& name,
313 const CookieChangedCallback& callback) override;
315 private:
316 // For queueing the cookie monster calls.
317 class CookieMonsterTask;
318 template <typename Result>
319 class DeleteTask;
320 class DeleteAllCreatedBetweenTask;
321 class DeleteAllCreatedBetweenForHostTask;
322 class DeleteAllForHostTask;
323 class DeleteAllTask;
324 class DeleteCookieTask;
325 class DeleteCanonicalCookieTask;
326 class GetAllCookiesForURLWithOptionsTask;
327 class GetAllCookiesTask;
328 class GetCookiesWithOptionsTask;
329 class SetAllCookiesTask;
330 class SetCookieWithDetailsTask;
331 class SetCookieWithOptionsTask;
332 class DeleteSessionCookiesTask;
333 class HasCookiesForETLDP1Task;
335 // Testing support.
336 // For SetCookieWithCreationTime.
337 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
338 TestCookieDeleteAllCreatedBetweenTimestamps);
339 // For SetCookieWithCreationTime.
340 FRIEND_TEST_ALL_PREFIXES(MultiThreadedCookieMonsterTest,
341 ThreadCheckDeleteAllCreatedBetweenForHost);
343 // For gargage collection constants.
344 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
345 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
346 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
347 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
349 // For validation of key values.
350 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
351 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
352 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
353 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
355 // For FindCookiesForKey.
356 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
358 // For ComputeCookieDiff.
359 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ComputeCookieDiff);
361 // Internal reasons for deletion, used to populate informative histograms
362 // and to provide a public cause for onCookieChange notifications.
364 // If you add or remove causes from this list, please be sure to also update
365 // the CookieMonsterDelegate::ChangeCause mapping inside ChangeCauseMapping.
366 // Moreover, these are used as array indexes, so avoid reordering to keep the
367 // histogram buckets consistent. New items (if necessary) should be added
368 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
369 enum DeletionCause {
370 DELETE_COOKIE_EXPLICIT = 0,
371 DELETE_COOKIE_OVERWRITE,
372 DELETE_COOKIE_EXPIRED,
373 DELETE_COOKIE_EVICTED,
374 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
375 DELETE_COOKIE_DONT_RECORD, // e.g. For final cleanup after flush to store.
376 DELETE_COOKIE_EVICTED_DOMAIN,
377 DELETE_COOKIE_EVICTED_GLOBAL,
379 // Cookies evicted during domain level garbage collection that
380 // were accessed longer ago than kSafeFromGlobalPurgeDays
381 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
383 // Cookies evicted during domain level garbage collection that
384 // were accessed more recently than kSafeFromGlobalPurgeDays
385 // (and thus would have been preserved by global garbage collection).
386 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
388 // A common idiom is to remove a cookie by overwriting it with an
389 // already-expired expiration date. This captures that case.
390 DELETE_COOKIE_EXPIRED_OVERWRITE,
392 // Cookies are not allowed to contain control characters in the name or
393 // value. However, we used to allow them, so we are now evicting any such
394 // cookies as we load them. See http://crbug.com/238041.
395 DELETE_COOKIE_CONTROL_CHAR,
397 DELETE_COOKIE_LAST_ENTRY
400 // The number of days since last access that cookies will not be subject
401 // to global garbage collection.
402 static const int kSafeFromGlobalPurgeDays;
404 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
405 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
407 ~CookieMonster() override;
409 // The following are synchronous calls to which the asynchronous methods
410 // delegate either immediately (if the store is loaded) or through a deferred
411 // task (if the store is not yet loaded).
412 bool SetCookieWithDetails(const GURL& url,
413 const std::string& name,
414 const std::string& value,
415 const std::string& domain,
416 const std::string& path,
417 const base::Time& expiration_time,
418 bool secure,
419 bool http_only,
420 bool first_party,
421 CookiePriority priority);
423 CookieList GetAllCookies();
425 CookieList GetAllCookiesForURLWithOptions(const GURL& url,
426 const CookieOptions& options);
428 CookieList GetAllCookiesForURL(const GURL& url);
430 int DeleteAll(bool sync_to_store);
432 int DeleteAllCreatedBetween(const base::Time& delete_begin,
433 const base::Time& delete_end);
435 int DeleteAllForHost(const GURL& url);
436 int DeleteAllCreatedBetweenForHost(const base::Time delete_begin,
437 const base::Time delete_end,
438 const GURL& url);
440 bool DeleteCanonicalCookie(const CanonicalCookie& cookie);
442 bool SetCookieWithOptions(const GURL& url,
443 const std::string& cookie_line,
444 const CookieOptions& options);
446 std::string GetCookiesWithOptions(const GURL& url,
447 const CookieOptions& options);
449 void DeleteCookie(const GURL& url, const std::string& cookie_name);
451 bool SetCookieWithCreationTime(const GURL& url,
452 const std::string& cookie_line,
453 const base::Time& creation_time);
455 int DeleteSessionCookies();
457 bool HasCookiesForETLDP1(const std::string& etldp1);
459 // Called by all non-static functions to ensure that the cookies store has
460 // been initialized. This is not done during creating so it doesn't block
461 // the window showing.
462 // Note: this method should always be called with lock_ held.
463 void InitIfNecessary() {
464 if (!initialized_) {
465 if (store_.get()) {
466 InitStore();
467 } else {
468 loaded_ = true;
470 initialized_ = true;
474 // Initializes the backing store and reads existing cookies from it.
475 // Should only be called by InitIfNecessary().
476 void InitStore();
478 // Stores cookies loaded from the backing store and invokes any deferred
479 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
480 // was invoked and is used for reporting histogram_time_blocked_on_load_.
481 // See PersistentCookieStore::Load for details on the contents of cookies.
482 void OnLoaded(base::TimeTicks beginning_time,
483 const std::vector<CanonicalCookie*>& cookies);
485 // Stores cookies loaded from the backing store and invokes the deferred
486 // task(s) pending loading of cookies associated with the domain key
487 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
488 // loaded from DB. See PersistentCookieStore::Load for details on the contents
489 // of cookies.
490 void OnKeyLoaded(const std::string& key,
491 const std::vector<CanonicalCookie*>& cookies);
493 // Stores the loaded cookies.
494 void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);
496 // Invokes deferred calls.
497 void InvokeQueue();
499 // Checks that |cookies_| matches our invariants, and tries to repair any
500 // inconsistencies. (In other words, it does not have duplicate cookies).
501 void EnsureCookiesMapIsValid();
503 // Checks for any duplicate cookies for CookieMap key |key| which lie between
504 // |begin| and |end|. If any are found, all but the most recent are deleted.
505 // Returns the number of duplicate cookies that were deleted.
506 int TrimDuplicateCookiesForKey(const std::string& key,
507 CookieMap::iterator begin,
508 CookieMap::iterator end);
510 void SetDefaultCookieableSchemes();
512 void FindCookiesForHostAndDomain(const GURL& url,
513 const CookieOptions& options,
514 bool update_access_time,
515 std::vector<CanonicalCookie*>* cookies);
517 void FindCookiesForKey(const std::string& key,
518 const GURL& url,
519 const CookieOptions& options,
520 const base::Time& current,
521 bool update_access_time,
522 std::vector<CanonicalCookie*>* cookies);
524 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
525 // If |skip_httponly| is true, httponly cookies will not be deleted. The
526 // return value with be true if |skip_httponly| skipped an httponly cookie.
527 // |key| is the key to find the cookie in cookies_; see the comment before
528 // the CookieMap typedef for details.
529 // NOTE: There should never be more than a single matching equivalent cookie.
530 bool DeleteAnyEquivalentCookie(const std::string& key,
531 const CanonicalCookie& ecc,
532 bool skip_httponly,
533 bool already_expired);
535 // Takes ownership of *cc. Returns an iterator that points to the inserted
536 // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
537 CookieMap::iterator InternalInsertCookie(const std::string& key,
538 CanonicalCookie* cc,
539 bool sync_to_store);
541 // Helper function that sets cookies with more control.
542 // Not exposed as we don't want callers to have the ability
543 // to specify (potentially duplicate) creation times.
544 bool SetCookieWithCreationTimeAndOptions(const GURL& url,
545 const std::string& cookie_line,
546 const base::Time& creation_time,
547 const CookieOptions& options);
549 // Helper function that sets a canonical cookie, deleting equivalents and
550 // performing garbage collection.
551 bool SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
552 const base::Time& creation_time,
553 const CookieOptions& options);
555 // Helper function calling SetCanonicalCookie() for all cookies in |list|.
556 bool SetCanonicalCookies(const CookieList& list);
558 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
559 const base::Time& current_time);
561 // |deletion_cause| argument is used for collecting statistics and choosing
562 // the correct CookieMonsterDelegate::ChangeCause for OnCookieChanged
563 // notifications. Guarantee: All iterators to cookies_ except to the
564 // deleted entry remain vaild.
565 void InternalDeleteCookie(CookieMap::iterator it,
566 bool sync_to_store,
567 DeletionCause deletion_cause);
569 // If the number of cookies for CookieMap key |key|, or globally, are
570 // over the preset maximums above, garbage collect, first for the host and
571 // then globally. See comments above garbage collection threshold
572 // constants for details.
574 // Returns the number of cookies deleted (useful for debugging).
575 int GarbageCollect(const base::Time& current, const std::string& key);
577 // Helper for GarbageCollect(); can be called directly as well. Deletes
578 // all expired cookies in |itpair|. If |cookie_its| is non-NULL, it is
579 // populated with all the non-expired cookies from |itpair|.
581 // Returns the number of cookies deleted.
582 int GarbageCollectExpired(const base::Time& current,
583 const CookieMapItPair& itpair,
584 std::vector<CookieMap::iterator>* cookie_its);
586 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
587 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
588 int GarbageCollectDeleteRange(const base::Time& current,
589 DeletionCause cause,
590 CookieItVector::iterator cookie_its_begin,
591 CookieItVector::iterator cookie_its_end);
593 // Find the key (for lookup in cookies_) based on the given domain.
594 // See comment on keys before the CookieMap typedef.
595 std::string GetKey(const std::string& domain) const;
597 bool HasCookieableScheme(const GURL& url);
599 // Statistics support
601 // This function should be called repeatedly, and will record
602 // statistics if a sufficient time period has passed.
603 void RecordPeriodicStats(const base::Time& current_time);
605 // Initialize the above variables; should only be called from
606 // the constructor.
607 void InitializeHistograms();
609 // The resolution of our time isn't enough, so we do something
610 // ugly and increment when we've seen the same time twice.
611 base::Time CurrentTime();
613 // Runs the task if, or defers the task until, the full cookie database is
614 // loaded.
615 void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);
617 // Runs the task if, or defers the task until, the cookies for the given URL
618 // are loaded.
619 void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
620 const GURL& url);
622 // Computes the difference between |old_cookies| and |new_cookies|, and writes
623 // the result in |cookies_to_add| and |cookies_to_delete|.
624 // This function has the side effect of changing the order of |old_cookies|
625 // and |new_cookies|. |cookies_to_add| and |cookies_to_delete| must be empty,
626 // and none of the arguments can be null.
627 void ComputeCookieDiff(CookieList* old_cookies,
628 CookieList* new_cookies,
629 CookieList* cookies_to_add,
630 CookieList* cookies_to_delete);
632 // Run all cookie changed callbacks that are monitoring |cookie|.
633 // |removed| is true if the cookie was deleted.
634 void RunCallbacks(const CanonicalCookie& cookie, bool removed);
636 // Histogram variables; see CookieMonster::InitializeHistograms() in
637 // cookie_monster.cc for details.
638 base::HistogramBase* histogram_expiration_duration_minutes_;
639 base::HistogramBase* histogram_between_access_interval_minutes_;
640 base::HistogramBase* histogram_evicted_last_access_minutes_;
641 base::HistogramBase* histogram_count_;
642 base::HistogramBase* histogram_domain_count_;
643 base::HistogramBase* histogram_etldp1_count_;
644 base::HistogramBase* histogram_domain_per_etldp1_count_;
645 base::HistogramBase* histogram_number_duplicate_db_cookies_;
646 base::HistogramBase* histogram_cookie_deletion_cause_;
647 base::HistogramBase* histogram_time_mac_;
648 base::HistogramBase* histogram_time_blocked_on_load_;
650 CookieMap cookies_;
652 // Indicates whether the cookie store has been initialized. This happens
653 // lazily in InitStoreIfNecessary().
654 bool initialized_;
656 // Indicates whether loading from the backend store is completed and
657 // calls may be immediately processed.
658 bool loaded_;
660 // List of domain keys that have been loaded from the DB.
661 std::set<std::string> keys_loaded_;
663 // Map of domain keys to their associated task queues. These tasks are blocked
664 // until all cookies for the associated domain key eTLD+1 are loaded from the
665 // backend store.
666 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask>>>
667 tasks_pending_for_key_;
669 // Queues tasks that are blocked until all cookies are loaded from the backend
670 // store.
671 std::queue<scoped_refptr<CookieMonsterTask>> tasks_pending_;
673 scoped_refptr<PersistentCookieStore> store_;
675 base::Time last_time_seen_;
677 // Minimum delay after updating a cookie's LastAccessDate before we will
678 // update it again.
679 const base::TimeDelta last_access_threshold_;
681 // Approximate date of access time of least recently accessed cookie
682 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
683 // to be before or equal to the actual time, and b) to be accurate
684 // immediately after a garbage collection that scans through all the cookies.
685 // This value is used to determine whether global garbage collection might
686 // find cookies to purge.
687 // Note: The default Time() constructor will create a value that compares
688 // earlier than any other time value, which is wanted. Thus this
689 // value is not initialized.
690 base::Time earliest_access_time_;
692 // During loading, holds the set of all loaded cookie creation times. Used to
693 // avoid ever letting cookies with duplicate creation times into the store;
694 // that way we don't have to worry about what sections of code are safe
695 // to call while it's in that state.
696 std::set<int64> creation_times_;
698 std::vector<std::string> cookieable_schemes_;
700 scoped_refptr<CookieMonsterDelegate> delegate_;
702 // Lock for thread-safety
703 base::Lock lock_;
705 base::Time last_statistic_record_time_;
707 bool keep_expired_cookies_;
708 bool persist_session_cookies_;
710 // Static setting for whether or not file scheme cookies are allows when
711 // a new CookieMonster is created, or the accepted schemes on a CookieMonster
712 // instance are reset back to defaults.
713 static bool default_enable_file_scheme_;
715 typedef std::map<std::pair<GURL, std::string>,
716 linked_ptr<CookieChangedCallbackList>> CookieChangedHookMap;
717 CookieChangedHookMap hook_map_;
719 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
722 class NET_EXPORT CookieMonsterDelegate
723 : public base::RefCountedThreadSafe<CookieMonsterDelegate> {
724 public:
725 // The publicly relevant reasons a cookie might be changed.
726 enum ChangeCause {
727 // The cookie was changed directly by a consumer's action.
728 CHANGE_COOKIE_EXPLICIT,
729 // The cookie was automatically removed due to an insert operation that
730 // overwrote it.
731 CHANGE_COOKIE_OVERWRITE,
732 // The cookie was automatically removed as it expired.
733 CHANGE_COOKIE_EXPIRED,
734 // The cookie was automatically evicted during garbage collection.
735 CHANGE_COOKIE_EVICTED,
736 // The cookie was overwritten with an already-expired expiration date.
737 CHANGE_COOKIE_EXPIRED_OVERWRITE
740 // Will be called when a cookie is added or removed. The function is passed
741 // the respective |cookie| which was added to or removed from the cookies.
742 // If |removed| is true, the cookie was deleted, and |cause| will be set
743 // to the reason for its removal. If |removed| is false, the cookie was
744 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
746 // As a special case, note that updating a cookie's properties is implemented
747 // as a two step process: the cookie to be updated is first removed entirely,
748 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
749 // a new cookie is written with the updated values, generating a notification
750 // with cause CHANGE_COOKIE_EXPLICIT.
751 virtual void OnCookieChanged(const CanonicalCookie& cookie,
752 bool removed,
753 ChangeCause cause) = 0;
754 protected:
755 friend class base::RefCountedThreadSafe<CookieMonsterDelegate>;
756 virtual ~CookieMonsterDelegate() {}
759 typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
760 RefcountedPersistentCookieStore;
762 class NET_EXPORT CookieMonster::PersistentCookieStore
763 : public RefcountedPersistentCookieStore {
764 public:
765 typedef base::Callback<void(const std::vector<CanonicalCookie*>&)>
766 LoadedCallback;
768 // Initializes the store and retrieves the existing cookies. This will be
769 // called only once at startup. The callback will return all the cookies
770 // that are not yet returned to CookieMonster by previous priority loads.
771 virtual void Load(const LoadedCallback& loaded_callback) = 0;
773 // Does a priority load of all cookies for the domain key (eTLD+1). The
774 // callback will return all the cookies that are not yet returned by previous
775 // loads, which includes cookies for the requested domain key if they are not
776 // already returned, plus all cookies that are chain-loaded and not yet
777 // returned to CookieMonster.
778 virtual void LoadCookiesForKey(const std::string& key,
779 const LoadedCallback& loaded_callback) = 0;
781 virtual void AddCookie(const CanonicalCookie& cc) = 0;
782 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
783 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
785 // Instructs the store to not discard session only cookies on shutdown.
786 virtual void SetForceKeepSessionState() = 0;
788 // Flushes the store and posts |callback| when complete.
789 virtual void Flush(const base::Closure& callback) = 0;
791 protected:
792 PersistentCookieStore() {}
793 virtual ~PersistentCookieStore() {}
795 private:
796 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
797 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
800 } // namespace net
802 #endif // NET_COOKIES_COOKIE_MONSTER_H_