ozone: drm: Crash immediately if no usable GPU is found
[chromium-blink-merge.git] / net / cookies / cookie_monster.h
blobced1c235f7f3151bba447b6a3e92132e3005672e
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;
156 // Sets a cookie given explicit user-provided cookie attributes. The cookie
157 // name, value, domain, etc. are each provided as separate strings. This
158 // function expects each attribute to be well-formed. It will check for
159 // disallowed characters (e.g. the ';' character is disallowed within the
160 // cookie value attribute) and will return false without setting the cookie
161 // if such characters are found.
162 void SetCookieWithDetailsAsync(const GURL& url,
163 const std::string& name,
164 const std::string& value,
165 const std::string& domain,
166 const std::string& path,
167 const base::Time& expiration_time,
168 bool secure,
169 bool http_only,
170 bool first_party,
171 CookiePriority priority,
172 const SetCookiesCallback& callback);
174 // Returns all the cookies, for use in management UI, etc. This does not mark
175 // the cookies as having been accessed.
176 // The returned cookies are ordered by longest path, then by earliest
177 // creation date.
178 void GetAllCookiesAsync(const GetCookieListCallback& callback);
180 // Returns all the cookies, for use in management UI, etc. Filters results
181 // using given url scheme, host / domain and path and options. This does not
182 // mark the cookies as having been accessed.
183 // The returned cookies are ordered by longest path, then earliest
184 // creation date.
185 void GetAllCookiesForURLWithOptionsAsync(
186 const GURL& url,
187 const CookieOptions& options,
188 const GetCookieListCallback& callback);
190 // Deletes all of the cookies.
191 void DeleteAllAsync(const DeleteCallback& callback);
193 // Deletes all cookies that match the host of the given URL
194 // regardless of path. This includes all http_only and secure cookies,
195 // but does not include any domain cookies that may apply to this host.
196 // Returns the number of cookies deleted.
197 void DeleteAllForHostAsync(const GURL& url, const DeleteCallback& callback);
199 // Deletes one specific cookie.
200 void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
201 const DeleteCookieCallback& callback);
203 // Resets the list of cookieable schemes to the supplied schemes. Does
204 // nothing if called after first use of the instance (i.e. after the
205 // instance initialization process).
206 void SetCookieableSchemes(const char* const schemes[], size_t num_schemes);
208 // Instructs the cookie monster to not delete expired cookies. This is used
209 // in cases where the cookie monster is used as a data structure to keep
210 // arbitrary cookies.
211 void SetKeepExpiredCookies();
213 // Protects session cookies from deletion on shutdown.
214 void SetForceKeepSessionState();
216 // Flush the backing store (if any) to disk and post the given callback when
217 // done.
218 // WARNING: THE CALLBACK WILL RUN ON A RANDOM THREAD. IT MUST BE THREAD SAFE.
219 // It may be posted to the current thread, or it may run on the thread that
220 // actually does the flushing. Your Task should generally post a notification
221 // to the thread you actually want to be notified on.
222 void FlushStore(const base::Closure& callback);
224 // Replaces all the cookies by |list|. This method does not flush the backend.
225 void SetAllCookiesAsync(const CookieList& list,
226 const SetCookiesCallback& callback);
228 // CookieStore implementation.
230 // Sets the cookies specified by |cookie_list| returned from |url|
231 // with options |options| in effect.
232 void SetCookieWithOptionsAsync(const GURL& url,
233 const std::string& cookie_line,
234 const CookieOptions& options,
235 const SetCookiesCallback& callback) override;
237 // Gets all cookies that apply to |url| given |options|.
238 // The returned cookies are ordered by longest path, then earliest
239 // creation date.
240 void GetCookiesWithOptionsAsync(const GURL& url,
241 const CookieOptions& options,
242 const GetCookiesCallback& callback) override;
244 // Invokes GetAllCookiesForURLWithOptions with options set to include HTTP
245 // only cookies.
246 void GetAllCookiesForURLAsync(const GURL& url,
247 const GetCookieListCallback& callback) override;
249 // Deletes all cookies with that might apply to |url| that has |cookie_name|.
250 void DeleteCookieAsync(const GURL& url,
251 const std::string& cookie_name,
252 const base::Closure& callback) override;
254 // Deletes all of the cookies that have a creation_date greater than or equal
255 // to |delete_begin| and less than |delete_end|.
256 // Returns the number of cookies that have been deleted.
257 void DeleteAllCreatedBetweenAsync(const base::Time& delete_begin,
258 const base::Time& delete_end,
259 const DeleteCallback& callback) override;
261 // Deletes all of the cookies that match the host of the given URL
262 // regardless of path and that have a creation_date greater than or
263 // equal to |delete_begin| and less then |delete_end|. This includes
264 // all http_only and secure cookies, but does not include any domain
265 // cookies that may apply to this host.
266 // Returns the number of cookies deleted.
267 void DeleteAllCreatedBetweenForHostAsync(
268 const base::Time delete_begin,
269 const base::Time delete_end,
270 const GURL& url,
271 const DeleteCallback& callback) override;
273 void DeleteSessionCookiesAsync(const DeleteCallback&) override;
275 CookieMonster* GetCookieMonster() override;
277 // Enables writing session cookies into the cookie database. If this this
278 // method is called, it must be called before first use of the instance
279 // (i.e. as part of the instance initialization process).
280 void SetPersistSessionCookies(bool persist_session_cookies);
282 // Debugging method to perform various validation checks on the map.
283 // Currently just checking that there are no null CanonicalCookie pointers
284 // in the map.
285 // Argument |arg| is to allow retaining of arbitrary data if the CHECKs
286 // in the function trip. TODO(rdsmith):Remove hack.
287 void ValidateMap(int arg);
289 // Determines if the scheme of the URL is a scheme that cookies will be
290 // stored for.
291 bool IsCookieableScheme(const std::string& scheme);
293 // The default list of schemes the cookie monster can handle.
294 static const char* const kDefaultCookieableSchemes[];
295 static const int kDefaultCookieableSchemesCount;
297 scoped_ptr<CookieChangedSubscription> AddCallbackForCookie(
298 const GURL& url,
299 const std::string& name,
300 const CookieChangedCallback& callback) override;
302 #if defined(OS_ANDROID)
303 // Resets the list of cookieable schemes to kDefaultCookieableSchemes with or
304 // without 'file' being included.
306 // There are some unknowns about how to correctly handle file:// cookies,
307 // and our implementation for this is not robust enough (Bug 1157243).
308 // This allows you to enable support, and is exposed as a public WebView
309 // API ('CookieManager::setAcceptFileSchemeCookies').
311 // TODO(mkwst): This method will be removed once we can deprecate and remove
312 // the Android WebView 'CookieManager::setAcceptFileSchemeCookies' method.
313 // Until then, this method only has effect on Android, and must not be used
314 // outside a WebView context.
315 void SetEnableFileScheme(bool accept);
316 #endif
318 private:
319 // For queueing the cookie monster calls.
320 class CookieMonsterTask;
321 template <typename Result>
322 class DeleteTask;
323 class DeleteAllCreatedBetweenTask;
324 class DeleteAllCreatedBetweenForHostTask;
325 class DeleteAllForHostTask;
326 class DeleteAllTask;
327 class DeleteCookieTask;
328 class DeleteCanonicalCookieTask;
329 class GetAllCookiesForURLWithOptionsTask;
330 class GetAllCookiesTask;
331 class GetCookiesWithOptionsTask;
332 class SetAllCookiesTask;
333 class SetCookieWithDetailsTask;
334 class SetCookieWithOptionsTask;
335 class DeleteSessionCookiesTask;
337 // Testing support.
338 // For SetCookieWithCreationTime.
339 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
340 TestCookieDeleteAllCreatedBetweenTimestamps);
341 // For SetCookieWithCreationTime.
342 FRIEND_TEST_ALL_PREFIXES(MultiThreadedCookieMonsterTest,
343 ThreadCheckDeleteAllCreatedBetweenForHost);
345 // For gargage collection constants.
346 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
347 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
348 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
349 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
351 // For validation of key values.
352 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
353 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
354 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
355 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
357 // For FindCookiesForKey.
358 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
360 // For ComputeCookieDiff.
361 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ComputeCookieDiff);
363 // For CookieSource histogram enum.
364 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, CookieSourceHistogram);
366 // Internal reasons for deletion, used to populate informative histograms
367 // and to provide a public cause for onCookieChange notifications.
369 // If you add or remove causes from this list, please be sure to also update
370 // the CookieMonsterDelegate::ChangeCause mapping inside ChangeCauseMapping.
371 // Moreover, these are used as array indexes, so avoid reordering to keep the
372 // histogram buckets consistent. New items (if necessary) should be added
373 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
374 enum DeletionCause {
375 DELETE_COOKIE_EXPLICIT = 0,
376 DELETE_COOKIE_OVERWRITE,
377 DELETE_COOKIE_EXPIRED,
378 DELETE_COOKIE_EVICTED,
379 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
380 DELETE_COOKIE_DONT_RECORD, // e.g. For final cleanup after flush to store.
381 DELETE_COOKIE_EVICTED_DOMAIN,
382 DELETE_COOKIE_EVICTED_GLOBAL,
384 // Cookies evicted during domain level garbage collection that
385 // were accessed longer ago than kSafeFromGlobalPurgeDays
386 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
388 // Cookies evicted during domain level garbage collection that
389 // were accessed more recently than kSafeFromGlobalPurgeDays
390 // (and thus would have been preserved by global garbage collection).
391 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
393 // A common idiom is to remove a cookie by overwriting it with an
394 // already-expired expiration date. This captures that case.
395 DELETE_COOKIE_EXPIRED_OVERWRITE,
397 // Cookies are not allowed to contain control characters in the name or
398 // value. However, we used to allow them, so we are now evicting any such
399 // cookies as we load them. See http://crbug.com/238041.
400 DELETE_COOKIE_CONTROL_CHAR,
402 DELETE_COOKIE_LAST_ENTRY
405 // This enum is used to generate a histogramed bitmask measureing the types
406 // of stored cookies. Please do not reorder the list when adding new entries.
407 // New items MUST be added at the end of the list, just before
408 // COOKIE_TYPE_LAST_ENTRY;
409 enum CookieType {
410 COOKIE_TYPE_FIRSTPARTYONLY = 0,
411 COOKIE_TYPE_HTTPONLY,
412 COOKIE_TYPE_SECURE,
413 COOKIE_TYPE_LAST_ENTRY
416 // Used to populate a histogram containing information about the
417 // sources of Secure and non-Secure cookies: that is, whether such
418 // cookies are set by origins with cryptographic or non-cryptographic
419 // schemes. Please do not reorder the list when adding new
420 // entries. New items MUST be added at the end of the list, just
421 // before COOKIE_SOURCE_LAST_ENTRY.
423 // COOKIE_SOURCE_(NON)SECURE_COOKIE_(NON)CRYPTOGRAPHIC_SCHEME means
424 // that a cookie was set or overwritten from a URL with the given type
425 // of scheme. This enum should not be used when cookies are *cleared*,
426 // because its purpose is to understand if Chrome can deprecate the
427 // ability of HTTP urls to set/overwrite Secure cookies.
428 enum CookieSource {
429 COOKIE_SOURCE_SECURE_COOKIE_CRYPTOGRAPHIC_SCHEME = 0,
430 COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
431 COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME,
432 COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
433 COOKIE_SOURCE_LAST_ENTRY
436 // The strategy for fetching cookies. Controlled by Finch experiment.
437 enum FetchStrategy {
438 // Fetches all cookies only when they're needed.
439 kFetchWhenNecessary = 0,
440 // Fetches all cookies as soon as any cookie is needed.
441 // This is the default behavior.
442 kAlwaysFetch,
443 // The fetch strategy is not yet determined.
444 kUnknownFetch,
447 // The number of days since last access that cookies will not be subject
448 // to global garbage collection.
449 static const int kSafeFromGlobalPurgeDays;
451 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
452 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
454 ~CookieMonster() override;
456 // The following are synchronous calls to which the asynchronous methods
457 // delegate either immediately (if the store is loaded) or through a deferred
458 // task (if the store is not yet loaded).
459 bool SetCookieWithDetails(const GURL& url,
460 const std::string& name,
461 const std::string& value,
462 const std::string& domain,
463 const std::string& path,
464 const base::Time& expiration_time,
465 bool secure,
466 bool http_only,
467 bool first_party,
468 CookiePriority priority);
470 CookieList GetAllCookies();
472 CookieList GetAllCookiesForURLWithOptions(const GURL& url,
473 const CookieOptions& options);
475 CookieList GetAllCookiesForURL(const GURL& url);
477 int DeleteAll(bool sync_to_store);
479 int DeleteAllCreatedBetween(const base::Time& delete_begin,
480 const base::Time& delete_end);
482 int DeleteAllForHost(const GURL& url);
483 int DeleteAllCreatedBetweenForHost(const base::Time delete_begin,
484 const base::Time delete_end,
485 const GURL& url);
487 bool DeleteCanonicalCookie(const CanonicalCookie& cookie);
489 bool SetCookieWithOptions(const GURL& url,
490 const std::string& cookie_line,
491 const CookieOptions& options);
493 std::string GetCookiesWithOptions(const GURL& url,
494 const CookieOptions& options);
496 void DeleteCookie(const GURL& url, const std::string& cookie_name);
498 bool SetCookieWithCreationTime(const GURL& url,
499 const std::string& cookie_line,
500 const base::Time& creation_time);
502 int DeleteSessionCookies();
504 // The first access to the cookie store initializes it. This method should be
505 // called before any access to the cookie store.
506 void MarkCookieStoreAsInitialized();
508 // Fetches all cookies if the backing store exists and they're not already
509 // being fetched.
510 // Note: this method should always be called with lock_ held.
511 void FetchAllCookiesIfNecessary();
513 // Fetches all cookies from the backing store.
514 // Note: this method should always be called with lock_ held.
515 void FetchAllCookies();
517 // Whether all cookies should be fetched as soon as any is requested.
518 bool ShouldFetchAllCookiesWhenFetchingAnyCookie();
520 // Stores cookies loaded from the backing store and invokes any deferred
521 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
522 // was invoked and is used for reporting histogram_time_blocked_on_load_.
523 // See PersistentCookieStore::Load for details on the contents of cookies.
524 void OnLoaded(base::TimeTicks beginning_time,
525 const std::vector<CanonicalCookie*>& cookies);
527 // Stores cookies loaded from the backing store and invokes the deferred
528 // task(s) pending loading of cookies associated with the domain key
529 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
530 // loaded from DB. See PersistentCookieStore::Load for details on the contents
531 // of cookies.
532 void OnKeyLoaded(const std::string& key,
533 const std::vector<CanonicalCookie*>& cookies);
535 // Stores the loaded cookies.
536 void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);
538 // Invokes deferred calls.
539 void InvokeQueue();
541 // Checks that |cookies_| matches our invariants, and tries to repair any
542 // inconsistencies. (In other words, it does not have duplicate cookies).
543 void EnsureCookiesMapIsValid();
545 // Checks for any duplicate cookies for CookieMap key |key| which lie between
546 // |begin| and |end|. If any are found, all but the most recent are deleted.
547 void TrimDuplicateCookiesForKey(const std::string& key,
548 CookieMap::iterator begin,
549 CookieMap::iterator end);
551 void SetDefaultCookieableSchemes();
553 void FindCookiesForHostAndDomain(const GURL& url,
554 const CookieOptions& options,
555 bool update_access_time,
556 std::vector<CanonicalCookie*>* cookies);
558 void FindCookiesForKey(const std::string& key,
559 const GURL& url,
560 const CookieOptions& options,
561 const base::Time& current,
562 bool update_access_time,
563 std::vector<CanonicalCookie*>* cookies);
565 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
566 // If |skip_httponly| is true, httponly cookies will not be deleted. The
567 // return value with be true if |skip_httponly| skipped an httponly cookie.
568 // |key| is the key to find the cookie in cookies_; see the comment before
569 // the CookieMap typedef for details.
570 // NOTE: There should never be more than a single matching equivalent cookie.
571 bool DeleteAnyEquivalentCookie(const std::string& key,
572 const CanonicalCookie& ecc,
573 bool skip_httponly,
574 bool already_expired);
576 // Takes ownership of *cc. Returns an iterator that points to the inserted
577 // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
578 CookieMap::iterator InternalInsertCookie(const std::string& key,
579 CanonicalCookie* cc,
580 bool sync_to_store);
582 // Helper function that sets cookies with more control.
583 // Not exposed as we don't want callers to have the ability
584 // to specify (potentially duplicate) creation times.
585 bool SetCookieWithCreationTimeAndOptions(const GURL& url,
586 const std::string& cookie_line,
587 const base::Time& creation_time,
588 const CookieOptions& options);
590 // Helper function that sets a canonical cookie, deleting equivalents and
591 // performing garbage collection.
592 bool SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
593 const base::Time& creation_time,
594 const CookieOptions& options);
596 // Helper function calling SetCanonicalCookie() for all cookies in |list|.
597 bool SetCanonicalCookies(const CookieList& list);
599 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
600 const base::Time& current_time);
602 // |deletion_cause| argument is used for collecting statistics and choosing
603 // the correct CookieMonsterDelegate::ChangeCause for OnCookieChanged
604 // notifications. Guarantee: All iterators to cookies_ except to the
605 // deleted entry remain vaild.
606 void InternalDeleteCookie(CookieMap::iterator it,
607 bool sync_to_store,
608 DeletionCause deletion_cause);
610 // If the number of cookies for CookieMap key |key|, or globally, are
611 // over the preset maximums above, garbage collect, first for the host and
612 // then globally. See comments above garbage collection threshold
613 // constants for details.
615 // Returns the number of cookies deleted (useful for debugging).
616 int GarbageCollect(const base::Time& current, const std::string& key);
618 // Helper for GarbageCollect(); can be called directly as well. Deletes
619 // all expired cookies in |itpair|. If |cookie_its| is non-NULL, it is
620 // populated with all the non-expired cookies from |itpair|.
622 // Returns the number of cookies deleted.
623 int GarbageCollectExpired(const base::Time& current,
624 const CookieMapItPair& itpair,
625 std::vector<CookieMap::iterator>* cookie_its);
627 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
628 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
629 int GarbageCollectDeleteRange(const base::Time& current,
630 DeletionCause cause,
631 CookieItVector::iterator cookie_its_begin,
632 CookieItVector::iterator cookie_its_end);
634 // Find the key (for lookup in cookies_) based on the given domain.
635 // See comment on keys before the CookieMap typedef.
636 std::string GetKey(const std::string& domain) const;
638 bool HasCookieableScheme(const GURL& url);
640 // Statistics support
642 // This function should be called repeatedly, and will record
643 // statistics if a sufficient time period has passed.
644 void RecordPeriodicStats(const base::Time& current_time);
646 // Initialize the above variables; should only be called from
647 // the constructor.
648 void InitializeHistograms();
650 // The resolution of our time isn't enough, so we do something
651 // ugly and increment when we've seen the same time twice.
652 base::Time CurrentTime();
654 // Runs the task if, or defers the task until, the full cookie database is
655 // loaded.
656 void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);
658 // Runs the task if, or defers the task until, the cookies for the given URL
659 // are loaded.
660 void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
661 const GURL& url);
663 // Computes the difference between |old_cookies| and |new_cookies|, and writes
664 // the result in |cookies_to_add| and |cookies_to_delete|.
665 // This function has the side effect of changing the order of |old_cookies|
666 // and |new_cookies|. |cookies_to_add| and |cookies_to_delete| must be empty,
667 // and none of the arguments can be null.
668 void ComputeCookieDiff(CookieList* old_cookies,
669 CookieList* new_cookies,
670 CookieList* cookies_to_add,
671 CookieList* cookies_to_delete);
673 // Run all cookie changed callbacks that are monitoring |cookie|.
674 // |removed| is true if the cookie was deleted.
675 void RunCallbacks(const CanonicalCookie& cookie, bool removed);
677 // Histogram variables; see CookieMonster::InitializeHistograms() in
678 // cookie_monster.cc for details.
679 base::HistogramBase* histogram_expiration_duration_minutes_;
680 base::HistogramBase* histogram_evicted_last_access_minutes_;
681 base::HistogramBase* histogram_count_;
682 base::HistogramBase* histogram_cookie_deletion_cause_;
683 base::HistogramBase* histogram_cookie_type_;
684 base::HistogramBase* histogram_cookie_source_scheme_;
685 base::HistogramBase* histogram_time_blocked_on_load_;
687 CookieMap cookies_;
689 // Indicates whether the cookie store has been initialized.
690 bool initialized_;
692 // Indicates whether the cookie store has started fetching all cookies.
693 bool started_fetching_all_cookies_;
694 // Indicates whether the cookie store has finished fetching all cookies.
695 bool finished_fetching_all_cookies_;
696 // The strategy to use for fetching cookies.
697 FetchStrategy fetch_strategy_;
699 // List of domain keys that have been loaded from the DB.
700 std::set<std::string> keys_loaded_;
702 // Map of domain keys to their associated task queues. These tasks are blocked
703 // until all cookies for the associated domain key eTLD+1 are loaded from the
704 // backend store.
705 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask>>>
706 tasks_pending_for_key_;
708 // Queues tasks that are blocked until all cookies are loaded from the backend
709 // store.
710 std::queue<scoped_refptr<CookieMonsterTask>> tasks_pending_;
712 scoped_refptr<PersistentCookieStore> store_;
714 base::Time last_time_seen_;
716 // Minimum delay after updating a cookie's LastAccessDate before we will
717 // update it again.
718 const base::TimeDelta last_access_threshold_;
720 // Approximate date of access time of least recently accessed cookie
721 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
722 // to be before or equal to the actual time, and b) to be accurate
723 // immediately after a garbage collection that scans through all the cookies.
724 // This value is used to determine whether global garbage collection might
725 // find cookies to purge.
726 // Note: The default Time() constructor will create a value that compares
727 // earlier than any other time value, which is wanted. Thus this
728 // value is not initialized.
729 base::Time earliest_access_time_;
731 // During loading, holds the set of all loaded cookie creation times. Used to
732 // avoid ever letting cookies with duplicate creation times into the store;
733 // that way we don't have to worry about what sections of code are safe
734 // to call while it's in that state.
735 std::set<int64> creation_times_;
737 std::vector<std::string> cookieable_schemes_;
739 scoped_refptr<CookieMonsterDelegate> delegate_;
741 // Lock for thread-safety
742 base::Lock lock_;
744 base::Time last_statistic_record_time_;
746 bool keep_expired_cookies_;
747 bool persist_session_cookies_;
749 // Static setting for whether or not file scheme cookies are allows when
750 // a new CookieMonster is created, or the accepted schemes on a CookieMonster
751 // instance are reset back to defaults.
752 static bool default_enable_file_scheme_;
754 typedef std::map<std::pair<GURL, std::string>,
755 linked_ptr<CookieChangedCallbackList>> CookieChangedHookMap;
756 CookieChangedHookMap hook_map_;
758 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
761 class NET_EXPORT CookieMonsterDelegate
762 : public base::RefCountedThreadSafe<CookieMonsterDelegate> {
763 public:
764 // The publicly relevant reasons a cookie might be changed.
765 enum ChangeCause {
766 // The cookie was changed directly by a consumer's action.
767 CHANGE_COOKIE_EXPLICIT,
768 // The cookie was automatically removed due to an insert operation that
769 // overwrote it.
770 CHANGE_COOKIE_OVERWRITE,
771 // The cookie was automatically removed as it expired.
772 CHANGE_COOKIE_EXPIRED,
773 // The cookie was automatically evicted during garbage collection.
774 CHANGE_COOKIE_EVICTED,
775 // The cookie was overwritten with an already-expired expiration date.
776 CHANGE_COOKIE_EXPIRED_OVERWRITE
779 // Will be called when a cookie is added or removed. The function is passed
780 // the respective |cookie| which was added to or removed from the cookies.
781 // If |removed| is true, the cookie was deleted, and |cause| will be set
782 // to the reason for its removal. If |removed| is false, the cookie was
783 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
785 // As a special case, note that updating a cookie's properties is implemented
786 // as a two step process: the cookie to be updated is first removed entirely,
787 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
788 // a new cookie is written with the updated values, generating a notification
789 // with cause CHANGE_COOKIE_EXPLICIT.
790 virtual void OnCookieChanged(const CanonicalCookie& cookie,
791 bool removed,
792 ChangeCause cause) = 0;
793 protected:
794 friend class base::RefCountedThreadSafe<CookieMonsterDelegate>;
795 virtual ~CookieMonsterDelegate() {}
798 typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
799 RefcountedPersistentCookieStore;
801 class NET_EXPORT CookieMonster::PersistentCookieStore
802 : public RefcountedPersistentCookieStore {
803 public:
804 typedef base::Callback<void(const std::vector<CanonicalCookie*>&)>
805 LoadedCallback;
807 // TODO(erikchen): Depending on the results of the cookie monster Finch
808 // experiment, update the name and description of this method. The behavior
809 // of this method doesn't change, but it has different semantics for the two
810 // different logic paths. See http://crbug.com/473483.
811 // Initializes the store and retrieves the existing cookies. This will be
812 // called only once at startup. The callback will return all the cookies
813 // that are not yet returned to CookieMonster by previous priority loads.
814 virtual void Load(const LoadedCallback& loaded_callback) = 0;
816 // Does a priority load of all cookies for the domain key (eTLD+1). The
817 // callback will return all the cookies that are not yet returned by previous
818 // loads, which includes cookies for the requested domain key if they are not
819 // already returned, plus all cookies that are chain-loaded and not yet
820 // returned to CookieMonster.
821 virtual void LoadCookiesForKey(const std::string& key,
822 const LoadedCallback& loaded_callback) = 0;
824 virtual void AddCookie(const CanonicalCookie& cc) = 0;
825 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
826 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
828 // Instructs the store to not discard session only cookies on shutdown.
829 virtual void SetForceKeepSessionState() = 0;
831 // Flushes the store and posts |callback| when complete.
832 virtual void Flush(const base::Closure& callback) = 0;
834 protected:
835 PersistentCookieStore() {}
836 virtual ~PersistentCookieStore() {}
838 private:
839 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
840 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
843 } // namespace net
845 #endif // NET_COOKIES_COOKIE_MONSTER_H_