blob: fc277140ec74646cc5c67cdc2053a8a8c0d41f85 [file] [log] [blame]
[email protected]63ee33bd2012-03-15 09:29:581// 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.
4
5// Brought to you by the letter D and the number 2.
6
7#ifndef NET_COOKIES_COOKIE_MONSTER_H_
8#define NET_COOKIES_COOKIE_MONSTER_H_
[email protected]63ee33bd2012-03-15 09:29:589
Avi Drissman13fc8932015-12-20 04:40:4610#include <stddef.h>
11#include <stdint.h>
12
[email protected]63ee33bd2012-03-15 09:29:5813#include <deque>
14#include <map>
15#include <queue>
16#include <set>
17#include <string>
18#include <utility>
19#include <vector>
20
[email protected]63ee33bd2012-03-15 09:29:5821#include "base/callback_forward.h"
22#include "base/gtest_prod_util.h"
Avi Drissman13fc8932015-12-20 04:40:4623#include "base/macros.h"
ellyjones399e35a22014-10-27 11:09:5624#include "base/memory/linked_ptr.h"
[email protected]63ee33bd2012-03-15 09:29:5825#include "base/memory/ref_counted.h"
26#include "base/memory/scoped_ptr.h"
27#include "base/synchronization/lock.h"
[email protected]9da992db2013-06-28 05:40:4728#include "base/time/time.h"
[email protected]565c3f42012-08-14 14:22:5829#include "net/base/net_export.h"
[email protected]8da4b1812012-07-25 13:54:3830#include "net/cookies/canonical_cookie.h"
[email protected]ab2d75c82013-04-19 18:39:0431#include "net/cookies/cookie_constants.h"
[email protected]63ee33bd2012-03-15 09:29:5832#include "net/cookies/cookie_store.h"
ellyjones399e35a22014-10-27 11:09:5633#include "url/gurl.h"
[email protected]63ee33bd2012-03-15 09:29:5834
35namespace base {
36class Histogram;
[email protected]de415552013-01-23 04:12:1737class HistogramBase;
[email protected]63ee33bd2012-03-15 09:29:5838class TimeTicks;
39} // namespace base
40
41namespace net {
42
[email protected]7c4b66b2014-01-04 12:28:1343class CookieMonsterDelegate;
[email protected]ebfe3172012-07-12 12:21:4144class ParsedCookie;
[email protected]63ee33bd2012-03-15 09:29:5845
46// The cookie monster is the system for storing and retrieving cookies. It has
47// an in-memory list of all cookies, and synchronizes non-session cookies to an
48// optional permanent storage that implements the PersistentCookieStore
49// interface.
50//
51// This class IS thread-safe. Normally, it is only used on the I/O thread, but
52// is also accessed directly through Automation for UI testing.
53//
mmenke96f3bab2016-01-22 17:34:0254// Tasks may be deferred if all affected cookies are not yet loaded from the
55// backing store. Otherwise, callbacks may be invoked immediately.
[email protected]63ee33bd2012-03-15 09:29:5856//
57// A cookie task is either pending loading of the entire cookie store, or
58// loading of cookies for a specfic domain key(eTLD+1). In the former case, the
[email protected]0184df32013-05-14 00:53:5559// cookie task will be queued in tasks_pending_ while PersistentCookieStore
60// chain loads the cookie store on DB thread. In the latter case, the cookie
61// task will be queued in tasks_pending_for_key_ while PermanentCookieStore
62// loads cookies for the specified domain key(eTLD+1) on DB thread.
[email protected]63ee33bd2012-03-15 09:29:5863//
64// Callbacks are guaranteed to be invoked on the calling thread.
65//
66// TODO(deanm) Implement CookieMonster, the cookie database.
67// - Verify that our domain enforcement and non-dotted handling is correct
68class NET_EXPORT CookieMonster : public CookieStore {
69 public:
[email protected]63ee33bd2012-03-15 09:29:5870 class PersistentCookieStore;
71
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.
87
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.
98
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;
[email protected]8ad5d462013-05-02 08:45:26110 typedef std::vector<CookieMap::iterator> CookieItVector;
111
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.
122 //
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;
130
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;
[email protected]63ee33bd2012-03-15 09:29:58135
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.
[email protected]7c4b66b2014-01-04 12:28:13142 CookieMonster(PersistentCookieStore* store, CookieMonsterDelegate* delegate);
[email protected]63ee33bd2012-03-15 09:29:58143
144 // Only used during unit testing.
145 CookieMonster(PersistentCookieStore* store,
[email protected]7c4b66b2014-01-04 12:28:13146 CookieMonsterDelegate* delegate,
[email protected]63ee33bd2012-03-15 09:29:58147 int last_access_threshold_milliseconds);
148
bartfaba13acdf2014-09-05 15:07:28149 // Helper function that adds all cookies from |list| into this instance,
150 // overwriting any equivalent cookies.
151 bool ImportCookies(const CookieList& list);
[email protected]63ee33bd2012-03-15 09:29:58152
153 typedef base::Callback<void(const CookieList& cookies)> GetCookieListCallback;
154 typedef base::Callback<void(bool success)> DeleteCookieCallback;
155
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,
[email protected]ab2d75c82013-04-19 18:39:04168 bool secure,
169 bool http_only,
mkwstae819bb2015-02-23 05:10:31170 bool first_party,
estarkcd39c11f2015-10-19 19:46:36171 bool enforce_prefixes,
jww601411a2015-11-20 19:46:57172 bool enforce_strict_secure,
[email protected]ab2d75c82013-04-19 18:39:04173 CookiePriority priority,
[email protected]63ee33bd2012-03-15 09:29:58174 const SetCookiesCallback& callback);
175
[email protected]63ee33bd2012-03-15 09:29:58176 // Returns all the cookies, for use in management UI, etc. This does not mark
177 // the cookies as having been accessed.
178 // The returned cookies are ordered by longest path, then by earliest
179 // creation date.
180 void GetAllCookiesAsync(const GetCookieListCallback& callback);
181
182 // Returns all the cookies, for use in management UI, etc. Filters results
183 // using given url scheme, host / domain and path and options. This does not
184 // mark the cookies as having been accessed.
185 // The returned cookies are ordered by longest path, then earliest
186 // creation date.
187 void GetAllCookiesForURLWithOptionsAsync(
188 const GURL& url,
189 const CookieOptions& options,
190 const GetCookieListCallback& callback);
191
[email protected]63ee33bd2012-03-15 09:29:58192 // Deletes all of the cookies.
193 void DeleteAllAsync(const DeleteCallback& callback);
194
195 // Deletes all cookies that match the host of the given URL
196 // regardless of path. This includes all http_only and secure cookies,
197 // but does not include any domain cookies that may apply to this host.
198 // Returns the number of cookies deleted.
mkwstbe84af312015-02-20 08:52:45199 void DeleteAllForHostAsync(const GURL& url, const DeleteCallback& callback);
[email protected]63ee33bd2012-03-15 09:29:58200
201 // Deletes one specific cookie.
202 void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
203 const DeleteCookieCallback& callback);
204
drogerd5d1278c2015-03-17 19:21:51205 // Replaces all the cookies by |list|. This method does not flush the backend.
206 void SetAllCookiesAsync(const CookieList& list,
207 const SetCookiesCallback& callback);
208
[email protected]63ee33bd2012-03-15 09:29:58209 // CookieStore implementation.
dchengb03027d2014-10-21 12:00:20210 void SetCookieWithOptionsAsync(const GURL& url,
211 const std::string& cookie_line,
212 const CookieOptions& options,
213 const SetCookiesCallback& callback) override;
dchengb03027d2014-10-21 12:00:20214 void GetCookiesWithOptionsAsync(const GURL& url,
215 const CookieOptions& options,
216 const GetCookiesCallback& callback) override;
dchengb03027d2014-10-21 12:00:20217 void GetAllCookiesForURLAsync(const GURL& url,
218 const GetCookieListCallback& callback) override;
dchengb03027d2014-10-21 12:00:20219 void DeleteCookieAsync(const GURL& url,
220 const std::string& cookie_name,
221 const base::Closure& callback) override;
dchengb03027d2014-10-21 12:00:20222 void DeleteAllCreatedBetweenAsync(const base::Time& delete_begin,
223 const base::Time& delete_end,
224 const DeleteCallback& callback) override;
dchengb03027d2014-10-21 12:00:20225 void DeleteAllCreatedBetweenForHostAsync(
[email protected]a67a1112013-12-19 19:04:02226 const base::Time delete_begin,
227 const base::Time delete_end,
228 const GURL& url,
mostynbba063d6032014-10-09 11:01:13229 const DeleteCallback& callback) override;
dchengb03027d2014-10-21 12:00:20230 void DeleteSessionCookiesAsync(const DeleteCallback&) override;
mmenke96f3bab2016-01-22 17:34:02231 void FlushStore(const base::Closure& callback) override;
[email protected]264807b2012-04-25 14:49:37232
dchengb03027d2014-10-21 12:00:20233 CookieMonster* GetCookieMonster() override;
[email protected]63ee33bd2012-03-15 09:29:58234
mmenke74bcbd52016-01-21 17:17:56235 // Resets the list of cookieable schemes to the supplied schemes. Does
236 // nothing if called after first use of the instance (i.e. after the
237 // instance initialization process).
238 void SetCookieableSchemes(const char* const schemes[], size_t num_schemes);
239
240 // Instructs the cookie monster to not delete expired cookies. This is used
241 // in cases where the cookie monster is used as a data structure to keep
242 // arbitrary cookies.
243 void SetKeepExpiredCookies();
244
245 // Protects session cookies from deletion on shutdown.
246 void SetForceKeepSessionState();
247
[email protected]63ee33bd2012-03-15 09:29:58248 // Enables writing session cookies into the cookie database. If this this
249 // method is called, it must be called before first use of the instance
250 // (i.e. as part of the instance initialization process).
251 void SetPersistSessionCookies(bool persist_session_cookies);
252
[email protected]97a3b6e2012-06-12 01:53:56253 // Determines if the scheme of the URL is a scheme that cookies will be
254 // stored for.
255 bool IsCookieableScheme(const std::string& scheme);
256
[email protected]63ee33bd2012-03-15 09:29:58257 // The default list of schemes the cookie monster can handle.
[email protected]5edff3c52014-06-23 20:27:48258 static const char* const kDefaultCookieableSchemes[];
[email protected]63ee33bd2012-03-15 09:29:58259 static const int kDefaultCookieableSchemesCount;
260
dcheng67be2b1f2014-10-27 21:47:29261 scoped_ptr<CookieChangedSubscription> AddCallbackForCookie(
ellyjones399e35a22014-10-27 11:09:56262 const GURL& url,
263 const std::string& name,
264 const CookieChangedCallback& callback) override;
265
mkwstb73bf8aa2015-03-31 07:33:45266#if defined(OS_ANDROID)
267 // Resets the list of cookieable schemes to kDefaultCookieableSchemes with or
268 // without 'file' being included.
269 //
270 // There are some unknowns about how to correctly handle file:// cookies,
271 // and our implementation for this is not robust enough (Bug 1157243).
272 // This allows you to enable support, and is exposed as a public WebView
273 // API ('CookieManager::setAcceptFileSchemeCookies').
274 //
275 // TODO(mkwst): This method will be removed once we can deprecate and remove
276 // the Android WebView 'CookieManager::setAcceptFileSchemeCookies' method.
277 // Until then, this method only has effect on Android, and must not be used
278 // outside a WebView context.
279 void SetEnableFileScheme(bool accept);
280#endif
281
[email protected]63ee33bd2012-03-15 09:29:58282 private:
283 // For queueing the cookie monster calls.
284 class CookieMonsterTask;
mkwstbe84af312015-02-20 08:52:45285 template <typename Result>
286 class DeleteTask;
[email protected]63ee33bd2012-03-15 09:29:58287 class DeleteAllCreatedBetweenTask;
[email protected]d8428d52013-08-07 06:58:25288 class DeleteAllCreatedBetweenForHostTask;
[email protected]63ee33bd2012-03-15 09:29:58289 class DeleteAllForHostTask;
290 class DeleteAllTask;
291 class DeleteCookieTask;
292 class DeleteCanonicalCookieTask;
293 class GetAllCookiesForURLWithOptionsTask;
294 class GetAllCookiesTask;
295 class GetCookiesWithOptionsTask;
drogerd5d1278c2015-03-17 19:21:51296 class SetAllCookiesTask;
[email protected]63ee33bd2012-03-15 09:29:58297 class SetCookieWithDetailsTask;
298 class SetCookieWithOptionsTask;
[email protected]264807b2012-04-25 14:49:37299 class DeleteSessionCookiesTask;
[email protected]63ee33bd2012-03-15 09:29:58300
301 // Testing support.
302 // For SetCookieWithCreationTime.
303 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
304 TestCookieDeleteAllCreatedBetweenTimestamps);
[email protected]d8428d52013-08-07 06:58:25305 // For SetCookieWithCreationTime.
306 FRIEND_TEST_ALL_PREFIXES(MultiThreadedCookieMonsterTest,
307 ThreadCheckDeleteAllCreatedBetweenForHost);
[email protected]63ee33bd2012-03-15 09:29:58308
309 // For gargage collection constants.
310 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
311 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
312 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
313 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
314
315 // For validation of key values.
316 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
317 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
318 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
319 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
320
321 // For FindCookiesForKey.
322 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
323
drogerd5d1278c2015-03-17 19:21:51324 // For ComputeCookieDiff.
325 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ComputeCookieDiff);
326
estark7feb65c2b2015-08-21 23:38:20327 // For CookieSource histogram enum.
328 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, CookieSourceHistogram);
329
jww31e32632015-12-16 23:38:34330 // For kSafeFromGlobalPurgeDays in CookieStore.
jwwa9a0d482015-12-16 18:19:41331 FRIEND_TEST_ALL_PREFIXES(CookieMonsterStrictSecureTest, EvictSecureCookies);
jww82d99c12015-11-25 18:39:53332
jww31e32632015-12-16 23:38:34333 // For CookieDeleteEquivalent histogram enum.
334 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
335 CookieDeleteEquivalentHistogramTest);
336 FRIEND_TEST_ALL_PREFIXES(CookieMonsterStrictSecureTest,
337 CookieDeleteEquivalentHistogramTest);
338
[email protected]63ee33bd2012-03-15 09:29:58339 // Internal reasons for deletion, used to populate informative histograms
340 // and to provide a public cause for onCookieChange notifications.
341 //
342 // If you add or remove causes from this list, please be sure to also update
[email protected]7c4b66b2014-01-04 12:28:13343 // the CookieMonsterDelegate::ChangeCause mapping inside ChangeCauseMapping.
344 // Moreover, these are used as array indexes, so avoid reordering to keep the
[email protected]63ee33bd2012-03-15 09:29:58345 // histogram buckets consistent. New items (if necessary) should be added
346 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
347 enum DeletionCause {
348 DELETE_COOKIE_EXPLICIT = 0,
349 DELETE_COOKIE_OVERWRITE,
350 DELETE_COOKIE_EXPIRED,
351 DELETE_COOKIE_EVICTED,
352 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
353 DELETE_COOKIE_DONT_RECORD, // e.g. For final cleanup after flush to store.
354 DELETE_COOKIE_EVICTED_DOMAIN,
355 DELETE_COOKIE_EVICTED_GLOBAL,
356
357 // Cookies evicted during domain level garbage collection that
358 // were accessed longer ago than kSafeFromGlobalPurgeDays
359 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
360
361 // Cookies evicted during domain level garbage collection that
362 // were accessed more recently than kSafeFromGlobalPurgeDays
363 // (and thus would have been preserved by global garbage collection).
364 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
365
366 // A common idiom is to remove a cookie by overwriting it with an
367 // already-expired expiration date. This captures that case.
368 DELETE_COOKIE_EXPIRED_OVERWRITE,
369
[email protected]6210ce52013-09-20 03:33:14370 // Cookies are not allowed to contain control characters in the name or
371 // value. However, we used to allow them, so we are now evicting any such
372 // cookies as we load them. See http://crbug.com/238041.
373 DELETE_COOKIE_CONTROL_CHAR,
374
jww82d99c12015-11-25 18:39:53375 // When strict secure cookies is enabled, non-secure cookies are evicted
376 // right after expired cookies.
377 DELETE_COOKIE_NON_SECURE,
378
[email protected]63ee33bd2012-03-15 09:29:58379 DELETE_COOKIE_LAST_ENTRY
380 };
381
mkwstc1aa4cc2015-04-03 19:57:45382 // This enum is used to generate a histogramed bitmask measureing the types
383 // of stored cookies. Please do not reorder the list when adding new entries.
384 // New items MUST be added at the end of the list, just before
385 // COOKIE_TYPE_LAST_ENTRY;
386 enum CookieType {
387 COOKIE_TYPE_FIRSTPARTYONLY = 0,
388 COOKIE_TYPE_HTTPONLY,
389 COOKIE_TYPE_SECURE,
390 COOKIE_TYPE_LAST_ENTRY
391 };
392
estark7feb65c2b2015-08-21 23:38:20393 // Used to populate a histogram containing information about the
394 // sources of Secure and non-Secure cookies: that is, whether such
395 // cookies are set by origins with cryptographic or non-cryptographic
396 // schemes. Please do not reorder the list when adding new
397 // entries. New items MUST be added at the end of the list, just
398 // before COOKIE_SOURCE_LAST_ENTRY.
399 //
400 // COOKIE_SOURCE_(NON)SECURE_COOKIE_(NON)CRYPTOGRAPHIC_SCHEME means
401 // that a cookie was set or overwritten from a URL with the given type
402 // of scheme. This enum should not be used when cookies are *cleared*,
403 // because its purpose is to understand if Chrome can deprecate the
404 // ability of HTTP urls to set/overwrite Secure cookies.
405 enum CookieSource {
406 COOKIE_SOURCE_SECURE_COOKIE_CRYPTOGRAPHIC_SCHEME = 0,
407 COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
408 COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME,
409 COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
410 COOKIE_SOURCE_LAST_ENTRY
411 };
412
jww31e32632015-12-16 23:38:34413 // Used to populate a histogram for cookie setting in the "delete equivalent"
414 // step. Measures total attempts to delete an equivalent cookie as well as if
415 // a cookie is found to delete, if a cookie is skipped because it is secure,
416 // and if it is skipped for being secure but would have been deleted
417 // otherwise. The last two are only possible if strict secure cookies is
418 // turned on and if an insecure origin attempts to a set a cookie where a
419 // cookie with the same name and secure attribute already exists.
420 //
421 // Enum for UMA. Do no reorder or remove entries. New entries must be place
422 // directly before COOKIE_DELETE_EQUIVALENT_LAST_ENTRY and histograms.xml must
423 // be updated accordingly.
424 enum CookieDeleteEquivalent {
425 COOKIE_DELETE_EQUIVALENT_ATTEMPT = 0,
426 COOKIE_DELETE_EQUIVALENT_FOUND,
427 COOKIE_DELETE_EQUIVALENT_SKIPPING_SECURE,
428 COOKIE_DELETE_EQUIVALENT_WOULD_HAVE_DELETED,
429 COOKIE_DELETE_EQUIVALENT_LAST_ENTRY
430 };
431
erikchen1dd72a72015-05-06 20:45:05432 // The strategy for fetching cookies. Controlled by Finch experiment.
433 enum FetchStrategy {
434 // Fetches all cookies only when they're needed.
435 kFetchWhenNecessary = 0,
436 // Fetches all cookies as soon as any cookie is needed.
437 // This is the default behavior.
438 kAlwaysFetch,
439 // The fetch strategy is not yet determined.
440 kUnknownFetch,
441 };
442
[email protected]63ee33bd2012-03-15 09:29:58443 // The number of days since last access that cookies will not be subject
444 // to global garbage collection.
445 static const int kSafeFromGlobalPurgeDays;
446
447 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
448 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
449
dchengb03027d2014-10-21 12:00:20450 ~CookieMonster() override;
[email protected]63ee33bd2012-03-15 09:29:58451
452 // The following are synchronous calls to which the asynchronous methods
453 // delegate either immediately (if the store is loaded) or through a deferred
454 // task (if the store is not yet loaded).
455 bool SetCookieWithDetails(const GURL& url,
456 const std::string& name,
457 const std::string& value,
458 const std::string& domain,
459 const std::string& path,
460 const base::Time& expiration_time,
[email protected]ab2d75c82013-04-19 18:39:04461 bool secure,
462 bool http_only,
mkwstae819bb2015-02-23 05:10:31463 bool first_party,
estarkcd39c11f2015-10-19 19:46:36464 bool enforce_prefixes,
jww601411a2015-11-20 19:46:57465 bool enforce_strict_secure,
[email protected]ab2d75c82013-04-19 18:39:04466 CookiePriority priority);
[email protected]63ee33bd2012-03-15 09:29:58467
468 CookieList GetAllCookies();
469
470 CookieList GetAllCookiesForURLWithOptions(const GURL& url,
471 const CookieOptions& options);
472
[email protected]63ee33bd2012-03-15 09:29:58473 int DeleteAll(bool sync_to_store);
474
475 int DeleteAllCreatedBetween(const base::Time& delete_begin,
476 const base::Time& delete_end);
477
478 int DeleteAllForHost(const GURL& url);
mmenke74bcbd52016-01-21 17:17:56479
[email protected]d8428d52013-08-07 06:58:25480 int DeleteAllCreatedBetweenForHost(const base::Time delete_begin,
481 const base::Time delete_end,
482 const GURL& url);
[email protected]63ee33bd2012-03-15 09:29:58483
484 bool DeleteCanonicalCookie(const CanonicalCookie& cookie);
485
486 bool SetCookieWithOptions(const GURL& url,
487 const std::string& cookie_line,
488 const CookieOptions& options);
489
490 std::string GetCookiesWithOptions(const GURL& url,
491 const CookieOptions& options);
492
[email protected]63ee33bd2012-03-15 09:29:58493 void DeleteCookie(const GURL& url, const std::string& cookie_name);
494
495 bool SetCookieWithCreationTime(const GURL& url,
496 const std::string& cookie_line,
497 const base::Time& creation_time);
498
[email protected]264807b2012-04-25 14:49:37499 int DeleteSessionCookies();
500
erikchen1dd72a72015-05-06 20:45:05501 // The first access to the cookie store initializes it. This method should be
502 // called before any access to the cookie store.
503 void MarkCookieStoreAsInitialized();
[email protected]63ee33bd2012-03-15 09:29:58504
erikchen1dd72a72015-05-06 20:45:05505 // Fetches all cookies if the backing store exists and they're not already
506 // being fetched.
507 // Note: this method should always be called with lock_ held.
508 void FetchAllCookiesIfNecessary();
509
510 // Fetches all cookies from the backing store.
511 // Note: this method should always be called with lock_ held.
512 void FetchAllCookies();
513
514 // Whether all cookies should be fetched as soon as any is requested.
515 bool ShouldFetchAllCookiesWhenFetchingAnyCookie();
[email protected]63ee33bd2012-03-15 09:29:58516
517 // Stores cookies loaded from the backing store and invokes any deferred
518 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
519 // was invoked and is used for reporting histogram_time_blocked_on_load_.
520 // See PersistentCookieStore::Load for details on the contents of cookies.
521 void OnLoaded(base::TimeTicks beginning_time,
522 const std::vector<CanonicalCookie*>& cookies);
523
524 // Stores cookies loaded from the backing store and invokes the deferred
525 // task(s) pending loading of cookies associated with the domain key
526 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
527 // loaded from DB. See PersistentCookieStore::Load for details on the contents
528 // of cookies.
mkwstbe84af312015-02-20 08:52:45529 void OnKeyLoaded(const std::string& key,
530 const std::vector<CanonicalCookie*>& cookies);
[email protected]63ee33bd2012-03-15 09:29:58531
532 // Stores the loaded cookies.
533 void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);
534
535 // Invokes deferred calls.
536 void InvokeQueue();
537
538 // Checks that |cookies_| matches our invariants, and tries to repair any
539 // inconsistencies. (In other words, it does not have duplicate cookies).
540 void EnsureCookiesMapIsValid();
541
542 // Checks for any duplicate cookies for CookieMap key |key| which lie between
543 // |begin| and |end|. If any are found, all but the most recent are deleted.
ellyjonescabf57422015-08-21 18:44:51544 void TrimDuplicateCookiesForKey(const std::string& key,
545 CookieMap::iterator begin,
546 CookieMap::iterator end);
[email protected]63ee33bd2012-03-15 09:29:58547
548 void SetDefaultCookieableSchemes();
549
550 void FindCookiesForHostAndDomain(const GURL& url,
551 const CookieOptions& options,
552 bool update_access_time,
553 std::vector<CanonicalCookie*>* cookies);
554
555 void FindCookiesForKey(const std::string& key,
556 const GURL& url,
557 const CookieOptions& options,
558 const base::Time& current,
559 bool update_access_time,
560 std::vector<CanonicalCookie*>* cookies);
561
562 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
563 // If |skip_httponly| is true, httponly cookies will not be deleted. The
jww601411a2015-11-20 19:46:57564 // return value will be true if |skip_httponly| skipped an httponly cookie or
565 // |enforce_strict_secure| is true and the cookie to
566 // delete was Secure and the scheme of |ecc| is insecure. |key| is the key to
567 // find the cookie in cookies_; see the comment before the CookieMap typedef
568 // for details.
[email protected]63ee33bd2012-03-15 09:29:58569 // NOTE: There should never be more than a single matching equivalent cookie.
570 bool DeleteAnyEquivalentCookie(const std::string& key,
571 const CanonicalCookie& ecc,
572 bool skip_httponly,
jww601411a2015-11-20 19:46:57573 bool already_expired,
574 bool enforce_strict_secure);
[email protected]63ee33bd2012-03-15 09:29:58575
[email protected]6210ce52013-09-20 03:33:14576 // 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);
[email protected]63ee33bd2012-03-15 09:29:58581
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);
589
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);
595
drogerd5d1278c2015-03-17 19:21:51596 // Helper function calling SetCanonicalCookie() for all cookies in |list|.
597 bool SetCanonicalCookies(const CookieList& list);
598
[email protected]63ee33bd2012-03-15 09:29:58599 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
600 const base::Time& current_time);
601
602 // |deletion_cause| argument is used for collecting statistics and choosing
[email protected]7c4b66b2014-01-04 12:28:13603 // the correct CookieMonsterDelegate::ChangeCause for OnCookieChanged
604 // notifications. Guarantee: All iterators to cookies_ except to the
605 // deleted entry remain vaild.
mkwstbe84af312015-02-20 08:52:45606 void InternalDeleteCookie(CookieMap::iterator it,
607 bool sync_to_store,
[email protected]63ee33bd2012-03-15 09:29:58608 DeletionCause deletion_cause);
609
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.
614 //
615 // Returns the number of cookies deleted (useful for debugging).
jww82d99c12015-11-25 18:39:53616 size_t GarbageCollect(const base::Time& current,
617 const std::string& key,
618 bool enforce_strict_secure);
[email protected]63ee33bd2012-03-15 09:29:58619
jww82d99c12015-11-25 18:39:53620 // Helper for GarbageCollect(); can be called directly as well. Deletes all
621 // expired cookies in |itpair|. If |cookie_its| is non-NULL, all the
622 // non-expired cookies from |itpair| are appended to |cookie_its|.
[email protected]63ee33bd2012-03-15 09:29:58623 //
624 // Returns the number of cookies deleted.
jww82d99c12015-11-25 18:39:53625 size_t GarbageCollectExpired(const base::Time& current,
626 const CookieMapItPair& itpair,
627 CookieItVector* cookie_its);
628
629 // Helper for GarbageCollect(). Deletes all cookies not marked Secure in
630 // |valid_cookies_its|. If |cookie_its| is non-NULL, all the Secure cookies
631 // from |itpair| are appended to |cookie_its|.
632 //
633 // Returns the numeber of cookies deleted.
634 size_t GarbageCollectNonSecure(const CookieItVector& valid_cookies,
635 CookieItVector* cookie_its);
[email protected]63ee33bd2012-03-15 09:29:58636
[email protected]8ad5d462013-05-02 08:45:26637 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
638 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
jww82d99c12015-11-25 18:39:53639 size_t GarbageCollectDeleteRange(const base::Time& current,
640 DeletionCause cause,
641 CookieItVector::iterator cookie_its_begin,
642 CookieItVector::iterator cookie_its_end);
643
644 // Helper for GarbageCollect(). Deletes cookies in |cookie_its| from least to
645 // most recently used, but only before |safe_date|. Also will stop deleting
646 // when the number of remaining cookies hits |purge_goal|.
647 size_t GarbageCollectLeastRecentlyAccessed(const base::Time& current,
648 const base::Time& safe_date,
649 size_t purge_goal,
650 CookieItVector cookie_its);
[email protected]63ee33bd2012-03-15 09:29:58651
davidben879199c2015-03-06 00:55:04652 // Find the key (for lookup in cookies_) based on the given domain.
653 // See comment on keys before the CookieMap typedef.
654 std::string GetKey(const std::string& domain) const;
655
[email protected]63ee33bd2012-03-15 09:29:58656 bool HasCookieableScheme(const GURL& url);
657
658 // Statistics support
659
660 // This function should be called repeatedly, and will record
661 // statistics if a sufficient time period has passed.
662 void RecordPeriodicStats(const base::Time& current_time);
663
664 // Initialize the above variables; should only be called from
665 // the constructor.
666 void InitializeHistograms();
667
668 // The resolution of our time isn't enough, so we do something
669 // ugly and increment when we've seen the same time twice.
670 base::Time CurrentTime();
671
672 // Runs the task if, or defers the task until, the full cookie database is
673 // loaded.
674 void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);
675
676 // Runs the task if, or defers the task until, the cookies for the given URL
677 // are loaded.
678 void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
mkwstbe84af312015-02-20 08:52:45679 const GURL& url);
[email protected]63ee33bd2012-03-15 09:29:58680
drogerd5d1278c2015-03-17 19:21:51681 // Computes the difference between |old_cookies| and |new_cookies|, and writes
682 // the result in |cookies_to_add| and |cookies_to_delete|.
683 // This function has the side effect of changing the order of |old_cookies|
684 // and |new_cookies|. |cookies_to_add| and |cookies_to_delete| must be empty,
685 // and none of the arguments can be null.
686 void ComputeCookieDiff(CookieList* old_cookies,
687 CookieList* new_cookies,
688 CookieList* cookies_to_add,
689 CookieList* cookies_to_delete);
690
msarda0aad8f02014-10-30 09:22:39691 // Run all cookie changed callbacks that are monitoring |cookie|.
692 // |removed| is true if the cookie was deleted.
693 void RunCallbacks(const CanonicalCookie& cookie, bool removed);
694
[email protected]63ee33bd2012-03-15 09:29:58695 // Histogram variables; see CookieMonster::InitializeHistograms() in
696 // cookie_monster.cc for details.
[email protected]de415552013-01-23 04:12:17697 base::HistogramBase* histogram_expiration_duration_minutes_;
[email protected]de415552013-01-23 04:12:17698 base::HistogramBase* histogram_evicted_last_access_minutes_;
699 base::HistogramBase* histogram_count_;
[email protected]de415552013-01-23 04:12:17700 base::HistogramBase* histogram_cookie_deletion_cause_;
mkwstc1aa4cc2015-04-03 19:57:45701 base::HistogramBase* histogram_cookie_type_;
estark7feb65c2b2015-08-21 23:38:20702 base::HistogramBase* histogram_cookie_source_scheme_;
jww31e32632015-12-16 23:38:34703 base::HistogramBase* histogram_cookie_delete_equivalent_;
[email protected]de415552013-01-23 04:12:17704 base::HistogramBase* histogram_time_blocked_on_load_;
[email protected]63ee33bd2012-03-15 09:29:58705
706 CookieMap cookies_;
707
erikchen1dd72a72015-05-06 20:45:05708 // Indicates whether the cookie store has been initialized.
[email protected]63ee33bd2012-03-15 09:29:58709 bool initialized_;
710
erikchen1dd72a72015-05-06 20:45:05711 // Indicates whether the cookie store has started fetching all cookies.
712 bool started_fetching_all_cookies_;
713 // Indicates whether the cookie store has finished fetching all cookies.
714 bool finished_fetching_all_cookies_;
715 // The strategy to use for fetching cookies.
716 FetchStrategy fetch_strategy_;
[email protected]63ee33bd2012-03-15 09:29:58717
718 // List of domain keys that have been loaded from the DB.
719 std::set<std::string> keys_loaded_;
720
721 // Map of domain keys to their associated task queues. These tasks are blocked
722 // until all cookies for the associated domain key eTLD+1 are loaded from the
723 // backend store.
mkwstbe84af312015-02-20 08:52:45724 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask>>>
[email protected]0184df32013-05-14 00:53:55725 tasks_pending_for_key_;
[email protected]63ee33bd2012-03-15 09:29:58726
727 // Queues tasks that are blocked until all cookies are loaded from the backend
728 // store.
mkwstbe84af312015-02-20 08:52:45729 std::queue<scoped_refptr<CookieMonsterTask>> tasks_pending_;
[email protected]63ee33bd2012-03-15 09:29:58730
731 scoped_refptr<PersistentCookieStore> store_;
732
733 base::Time last_time_seen_;
734
735 // Minimum delay after updating a cookie's LastAccessDate before we will
736 // update it again.
737 const base::TimeDelta last_access_threshold_;
738
739 // Approximate date of access time of least recently accessed cookie
740 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
741 // to be before or equal to the actual time, and b) to be accurate
742 // immediately after a garbage collection that scans through all the cookies.
743 // This value is used to determine whether global garbage collection might
744 // find cookies to purge.
745 // Note: The default Time() constructor will create a value that compares
746 // earlier than any other time value, which is wanted. Thus this
747 // value is not initialized.
748 base::Time earliest_access_time_;
749
750 // During loading, holds the set of all loaded cookie creation times. Used to
751 // avoid ever letting cookies with duplicate creation times into the store;
752 // that way we don't have to worry about what sections of code are safe
753 // to call while it's in that state.
Avi Drissman13fc8932015-12-20 04:40:46754 std::set<int64_t> creation_times_;
[email protected]63ee33bd2012-03-15 09:29:58755
756 std::vector<std::string> cookieable_schemes_;
757
[email protected]7c4b66b2014-01-04 12:28:13758 scoped_refptr<CookieMonsterDelegate> delegate_;
[email protected]63ee33bd2012-03-15 09:29:58759
760 // Lock for thread-safety
761 base::Lock lock_;
762
763 base::Time last_statistic_record_time_;
764
765 bool keep_expired_cookies_;
766 bool persist_session_cookies_;
767
[email protected]97a3b6e2012-06-12 01:53:56768 // Static setting for whether or not file scheme cookies are allows when
769 // a new CookieMonster is created, or the accepted schemes on a CookieMonster
770 // instance are reset back to defaults.
771 static bool default_enable_file_scheme_;
[email protected]63ee33bd2012-03-15 09:29:58772
ellyjones399e35a22014-10-27 11:09:56773 typedef std::map<std::pair<GURL, std::string>,
774 linked_ptr<CookieChangedCallbackList>> CookieChangedHookMap;
775 CookieChangedHookMap hook_map_;
776
[email protected]63ee33bd2012-03-15 09:29:58777 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
778};
779
[email protected]7c4b66b2014-01-04 12:28:13780class NET_EXPORT CookieMonsterDelegate
781 : public base::RefCountedThreadSafe<CookieMonsterDelegate> {
[email protected]63ee33bd2012-03-15 09:29:58782 public:
783 // The publicly relevant reasons a cookie might be changed.
784 enum ChangeCause {
785 // The cookie was changed directly by a consumer's action.
786 CHANGE_COOKIE_EXPLICIT,
787 // The cookie was automatically removed due to an insert operation that
788 // overwrote it.
789 CHANGE_COOKIE_OVERWRITE,
790 // The cookie was automatically removed as it expired.
791 CHANGE_COOKIE_EXPIRED,
792 // The cookie was automatically evicted during garbage collection.
793 CHANGE_COOKIE_EVICTED,
794 // The cookie was overwritten with an already-expired expiration date.
795 CHANGE_COOKIE_EXPIRED_OVERWRITE
796 };
797
798 // Will be called when a cookie is added or removed. The function is passed
799 // the respective |cookie| which was added to or removed from the cookies.
800 // If |removed| is true, the cookie was deleted, and |cause| will be set
[email protected]a2c92a1c2012-04-03 12:32:14801 // to the reason for its removal. If |removed| is false, the cookie was
[email protected]63ee33bd2012-03-15 09:29:58802 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
803 //
804 // As a special case, note that updating a cookie's properties is implemented
805 // as a two step process: the cookie to be updated is first removed entirely,
806 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
807 // a new cookie is written with the updated values, generating a notification
808 // with cause CHANGE_COOKIE_EXPLICIT.
[email protected]5b9bc352012-07-18 13:13:34809 virtual void OnCookieChanged(const CanonicalCookie& cookie,
[email protected]63ee33bd2012-03-15 09:29:58810 bool removed,
811 ChangeCause cause) = 0;
812 protected:
[email protected]7c4b66b2014-01-04 12:28:13813 friend class base::RefCountedThreadSafe<CookieMonsterDelegate>;
814 virtual ~CookieMonsterDelegate() {}
[email protected]63ee33bd2012-03-15 09:29:58815};
816
[email protected]63ee33bd2012-03-15 09:29:58817typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
818 RefcountedPersistentCookieStore;
819
[email protected]c1b6e102013-04-10 20:54:49820class NET_EXPORT CookieMonster::PersistentCookieStore
[email protected]63ee33bd2012-03-15 09:29:58821 : public RefcountedPersistentCookieStore {
822 public:
[email protected]5b9bc352012-07-18 13:13:34823 typedef base::Callback<void(const std::vector<CanonicalCookie*>&)>
824 LoadedCallback;
[email protected]63ee33bd2012-03-15 09:29:58825
erikchen1dd72a72015-05-06 20:45:05826 // TODO(erikchen): Depending on the results of the cookie monster Finch
827 // experiment, update the name and description of this method. The behavior
828 // of this method doesn't change, but it has different semantics for the two
829 // different logic paths. See http://crbug.com/473483.
[email protected]63ee33bd2012-03-15 09:29:58830 // Initializes the store and retrieves the existing cookies. This will be
831 // called only once at startup. The callback will return all the cookies
832 // that are not yet returned to CookieMonster by previous priority loads.
833 virtual void Load(const LoadedCallback& loaded_callback) = 0;
834
835 // Does a priority load of all cookies for the domain key (eTLD+1). The
836 // callback will return all the cookies that are not yet returned by previous
837 // loads, which includes cookies for the requested domain key if they are not
838 // already returned, plus all cookies that are chain-loaded and not yet
839 // returned to CookieMonster.
840 virtual void LoadCookiesForKey(const std::string& key,
[email protected]dedec0b2013-02-28 04:50:10841 const LoadedCallback& loaded_callback) = 0;
[email protected]63ee33bd2012-03-15 09:29:58842
843 virtual void AddCookie(const CanonicalCookie& cc) = 0;
844 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
845 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
846
[email protected]bf510ed2012-06-05 08:31:43847 // Instructs the store to not discard session only cookies on shutdown.
848 virtual void SetForceKeepSessionState() = 0;
[email protected]63ee33bd2012-03-15 09:29:58849
850 // Flushes the store and posts |callback| when complete.
851 virtual void Flush(const base::Closure& callback) = 0;
852
853 protected:
854 PersistentCookieStore() {}
[email protected]a9813302012-04-28 09:29:28855 virtual ~PersistentCookieStore() {}
[email protected]63ee33bd2012-03-15 09:29:58856
857 private:
[email protected]a9813302012-04-28 09:29:28858 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
[email protected]63ee33bd2012-03-15 09:29:58859 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
860};
861
[email protected]63ee33bd2012-03-15 09:29:58862} // namespace net
863
864#endif // NET_COOKIES_COOKIE_MONSTER_H_