blob: 421e7d0c60548dd150911412e6baf708a0a95379 [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"
mmenkebe0910d2016-03-01 19:09:0927#include "base/memory/weak_ptr.h"
28#include "base/threading/thread_checker.h"
[email protected]9da992db2013-06-28 05:40:4729#include "base/time/time.h"
[email protected]565c3f42012-08-14 14:22:5830#include "net/base/net_export.h"
[email protected]8da4b1812012-07-25 13:54:3831#include "net/cookies/canonical_cookie.h"
[email protected]ab2d75c82013-04-19 18:39:0432#include "net/cookies/cookie_constants.h"
[email protected]63ee33bd2012-03-15 09:29:5833#include "net/cookies/cookie_store.h"
ellyjones399e35a22014-10-27 11:09:5634#include "url/gurl.h"
[email protected]63ee33bd2012-03-15 09:29:5835
36namespace base {
37class Histogram;
[email protected]de415552013-01-23 04:12:1738class HistogramBase;
[email protected]63ee33bd2012-03-15 09:29:5839class TimeTicks;
40} // namespace base
41
42namespace net {
43
[email protected]7c4b66b2014-01-04 12:28:1344class CookieMonsterDelegate;
[email protected]ebfe3172012-07-12 12:21:4145class ParsedCookie;
[email protected]63ee33bd2012-03-15 09:29:5846
47// The cookie monster is the system for storing and retrieving cookies. It has
48// an in-memory list of all cookies, and synchronizes non-session cookies to an
49// optional permanent storage that implements the PersistentCookieStore
50// interface.
51//
mmenke96f3bab2016-01-22 17:34:0252// Tasks may be deferred if all affected cookies are not yet loaded from the
53// backing store. Otherwise, callbacks may be invoked immediately.
[email protected]63ee33bd2012-03-15 09:29:5854//
55// A cookie task is either pending loading of the entire cookie store, or
56// loading of cookies for a specfic domain key(eTLD+1). In the former case, the
[email protected]0184df32013-05-14 00:53:5557// cookie task will be queued in tasks_pending_ while PersistentCookieStore
58// chain loads the cookie store on DB thread. In the latter case, the cookie
59// task will be queued in tasks_pending_for_key_ while PermanentCookieStore
60// loads cookies for the specified domain key(eTLD+1) on DB thread.
[email protected]63ee33bd2012-03-15 09:29:5861//
[email protected]63ee33bd2012-03-15 09:29:5862// TODO(deanm) Implement CookieMonster, the cookie database.
63// - Verify that our domain enforcement and non-dotted handling is correct
64class NET_EXPORT CookieMonster : public CookieStore {
65 public:
[email protected]63ee33bd2012-03-15 09:29:5866 class PersistentCookieStore;
67
68 // Terminology:
69 // * The 'top level domain' (TLD) of an internet domain name is
70 // the terminal "." free substring (e.g. "com" for google.com
71 // or world.std.com).
72 // * The 'effective top level domain' (eTLD) is the longest
73 // "." initiated terminal substring of an internet domain name
74 // that is controlled by a general domain registrar.
75 // (e.g. "co.uk" for news.bbc.co.uk).
76 // * The 'effective top level domain plus one' (eTLD+1) is the
77 // shortest "." delimited terminal substring of an internet
78 // domain name that is not controlled by a general domain
79 // registrar (e.g. "bbc.co.uk" for news.bbc.co.uk, or
80 // "google.com" for news.google.com). The general assumption
81 // is that all hosts and domains under an eTLD+1 share some
82 // administrative control.
83
84 // CookieMap is the central data structure of the CookieMonster. It
85 // is a map whose values are pointers to CanonicalCookie data
86 // structures (the data structures are owned by the CookieMonster
87 // and must be destroyed when removed from the map). The key is based on the
88 // effective domain of the cookies. If the domain of the cookie has an
89 // eTLD+1, that is the key for the map. If the domain of the cookie does not
90 // have an eTLD+1, the key of the map is the host the cookie applies to (it is
91 // not legal to have domain cookies without an eTLD+1). This rule
92 // excludes cookies for, e.g, ".com", ".co.uk", or ".internalnetwork".
93 // This behavior is the same as the behavior in Firefox v 3.6.10.
94
95 // NOTE(deanm):
96 // I benchmarked hash_multimap vs multimap. We're going to be query-heavy
97 // so it would seem like hashing would help. However they were very
98 // close, with multimap being a tiny bit faster. I think this is because
99 // our map is at max around 1000 entries, and the additional complexity
100 // for the hashing might not overcome the O(log(1000)) for querying
101 // a multimap. Also, multimap is standard, another reason to use it.
102 // TODO(rdsmith): This benchmark should be re-done now that we're allowing
103 // subtantially more entries in the map.
104 typedef std::multimap<std::string, CanonicalCookie*> CookieMap;
105 typedef std::pair<CookieMap::iterator, CookieMap::iterator> CookieMapItPair;
[email protected]8ad5d462013-05-02 08:45:26106 typedef std::vector<CookieMap::iterator> CookieItVector;
107
108 // Cookie garbage collection thresholds. Based off of the Mozilla defaults.
109 // When the number of cookies gets to k{Domain,}MaxCookies
110 // purge down to k{Domain,}MaxCookies - k{Domain,}PurgeCookies.
111 // It might seem scary to have a high purge value, but really it's not.
112 // You just make sure that you increase the max to cover the increase
113 // in purge, and we would have been purging the same number of cookies.
114 // We're just going through the garbage collection process less often.
115 // Note that the DOMAIN values are per eTLD+1; see comment for the
116 // CookieMap typedef. So, e.g., the maximum number of cookies allowed for
117 // google.com and all of its subdomains will be 150-180.
118 //
119 // Any cookies accessed more recently than kSafeFromGlobalPurgeDays will not
120 // be evicted by global garbage collection, even if we have more than
121 // kMaxCookies. This does not affect domain garbage collection.
122 static const size_t kDomainMaxCookies;
123 static const size_t kDomainPurgeCookies;
124 static const size_t kMaxCookies;
125 static const size_t kPurgeCookies;
126
127 // Quota for cookies with {low, medium, high} priorities within a domain.
mkwst87734352016-03-03 17:36:23128 static const size_t kDomainCookiesQuotaLow;
129 static const size_t kDomainCookiesQuotaMedium;
130 static const size_t kDomainCookiesQuotaHigh;
[email protected]63ee33bd2012-03-15 09:29:58131
132 // The store passed in should not have had Init() called on it yet. This
133 // class will take care of initializing it. The backing store is NOT owned by
134 // this class, but it must remain valid for the duration of the cookie
135 // monster's existence. If |store| is NULL, then no backing store will be
136 // updated. If |delegate| is non-NULL, it will be notified on
137 // creation/deletion of cookies.
[email protected]7c4b66b2014-01-04 12:28:13138 CookieMonster(PersistentCookieStore* store, CookieMonsterDelegate* delegate);
[email protected]63ee33bd2012-03-15 09:29:58139
140 // Only used during unit testing.
141 CookieMonster(PersistentCookieStore* store,
[email protected]7c4b66b2014-01-04 12:28:13142 CookieMonsterDelegate* delegate,
[email protected]63ee33bd2012-03-15 09:29:58143 int last_access_threshold_milliseconds);
144
mmenke606c59c2016-03-07 18:20:55145 ~CookieMonster() override;
146
drogerd5d1278c2015-03-17 19:21:51147 // Replaces all the cookies by |list|. This method does not flush the backend.
148 void SetAllCookiesAsync(const CookieList& list,
149 const SetCookiesCallback& callback);
150
[email protected]63ee33bd2012-03-15 09:29:58151 // CookieStore implementation.
dchengb03027d2014-10-21 12:00:20152 void SetCookieWithOptionsAsync(const GURL& url,
153 const std::string& cookie_line,
154 const CookieOptions& options,
155 const SetCookiesCallback& callback) override;
mmenkeea4cd402016-02-02 04:03:10156 void SetCookieWithDetailsAsync(const GURL& url,
157 const std::string& name,
158 const std::string& value,
159 const std::string& domain,
160 const std::string& path,
mmenkefdd4fc72016-02-05 20:53:24161 base::Time creation_time,
162 base::Time expiration_time,
163 base::Time last_access_time,
mmenkeea4cd402016-02-02 04:03:10164 bool secure,
165 bool http_only,
166 bool same_site,
167 bool enforce_strict_secure,
168 CookiePriority priority,
169 const SetCookiesCallback& callback) override;
dchengb03027d2014-10-21 12:00:20170 void GetCookiesWithOptionsAsync(const GURL& url,
171 const CookieOptions& options,
172 const GetCookiesCallback& callback) override;
mkwstc611e6d2016-02-23 15:45:55173 void GetCookieListWithOptionsAsync(
174 const GURL& url,
175 const CookieOptions& options,
176 const GetCookieListCallback& callback) override;
mmenke9fa44f2d2016-01-22 23:36:39177 void GetAllCookiesAsync(const GetCookieListCallback& callback) override;
dchengb03027d2014-10-21 12:00:20178 void DeleteCookieAsync(const GURL& url,
179 const std::string& cookie_name,
180 const base::Closure& callback) override;
mmenke24379d52016-02-05 23:50:17181 void DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
182 const DeleteCallback& callback) override;
dchengb03027d2014-10-21 12:00:20183 void DeleteAllCreatedBetweenAsync(const base::Time& delete_begin,
184 const base::Time& delete_end,
185 const DeleteCallback& callback) override;
dchengb03027d2014-10-21 12:00:20186 void DeleteAllCreatedBetweenForHostAsync(
[email protected]a67a1112013-12-19 19:04:02187 const base::Time delete_begin,
188 const base::Time delete_end,
189 const GURL& url,
mostynbba063d6032014-10-09 11:01:13190 const DeleteCallback& callback) override;
dchengb03027d2014-10-21 12:00:20191 void DeleteSessionCookiesAsync(const DeleteCallback&) override;
mmenke96f3bab2016-01-22 17:34:02192 void FlushStore(const base::Closure& callback) override;
mmenkeded79da2016-02-06 08:28:51193 void SetForceKeepSessionState() override;
[email protected]264807b2012-04-25 14:49:37194
mmenke74bcbd52016-01-21 17:17:56195 // Resets the list of cookieable schemes to the supplied schemes. Does
196 // nothing if called after first use of the instance (i.e. after the
197 // instance initialization process).
mmenke18dd8ba2016-02-01 18:42:10198 void SetCookieableSchemes(const std::vector<std::string>& schemes);
mmenke74bcbd52016-01-21 17:17:56199
[email protected]63ee33bd2012-03-15 09:29:58200 // Enables writing session cookies into the cookie database. If this this
201 // method is called, it must be called before first use of the instance
202 // (i.e. as part of the instance initialization process).
203 void SetPersistSessionCookies(bool persist_session_cookies);
204
[email protected]97a3b6e2012-06-12 01:53:56205 // Determines if the scheme of the URL is a scheme that cookies will be
206 // stored for.
207 bool IsCookieableScheme(const std::string& scheme);
208
[email protected]63ee33bd2012-03-15 09:29:58209 // The default list of schemes the cookie monster can handle.
[email protected]5edff3c52014-06-23 20:27:48210 static const char* const kDefaultCookieableSchemes[];
[email protected]63ee33bd2012-03-15 09:29:58211 static const int kDefaultCookieableSchemesCount;
212
dcheng67be2b1f2014-10-27 21:47:29213 scoped_ptr<CookieChangedSubscription> AddCallbackForCookie(
ellyjones399e35a22014-10-27 11:09:56214 const GURL& url,
215 const std::string& name,
216 const CookieChangedCallback& callback) override;
217
nharper5babb5e62016-03-09 18:58:07218 bool IsEphemeral() override;
219
[email protected]63ee33bd2012-03-15 09:29:58220 private:
221 // For queueing the cookie monster calls.
222 class CookieMonsterTask;
mkwstbe84af312015-02-20 08:52:45223 template <typename Result>
224 class DeleteTask;
[email protected]63ee33bd2012-03-15 09:29:58225 class DeleteAllCreatedBetweenTask;
[email protected]d8428d52013-08-07 06:58:25226 class DeleteAllCreatedBetweenForHostTask;
[email protected]63ee33bd2012-03-15 09:29:58227 class DeleteCookieTask;
228 class DeleteCanonicalCookieTask;
mkwst72b65162016-02-22 19:58:54229 class GetCookieListForURLWithOptionsTask;
[email protected]63ee33bd2012-03-15 09:29:58230 class GetAllCookiesTask;
231 class GetCookiesWithOptionsTask;
mkwstc611e6d2016-02-23 15:45:55232 class GetCookieListWithOptionsTask;
drogerd5d1278c2015-03-17 19:21:51233 class SetAllCookiesTask;
[email protected]63ee33bd2012-03-15 09:29:58234 class SetCookieWithDetailsTask;
235 class SetCookieWithOptionsTask;
[email protected]264807b2012-04-25 14:49:37236 class DeleteSessionCookiesTask;
[email protected]63ee33bd2012-03-15 09:29:58237
238 // Testing support.
239 // For SetCookieWithCreationTime.
240 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
241 TestCookieDeleteAllCreatedBetweenTimestamps);
242
243 // For gargage collection constants.
244 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestHostGarbageCollection);
245 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestTotalGarbageCollection);
246 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GarbageCollectionTriggers);
247 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGCTimes);
248
249 // For validation of key values.
250 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestDomainTree);
251 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestImport);
252 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, GetKey);
253 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, TestGetKey);
254
255 // For FindCookiesForKey.
256 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ShortLivedSessionCookies);
257
drogerd5d1278c2015-03-17 19:21:51258 // For ComputeCookieDiff.
259 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, ComputeCookieDiff);
260
estark7feb65c2b2015-08-21 23:38:20261 // For CookieSource histogram enum.
262 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest, CookieSourceHistogram);
263
jww31e32632015-12-16 23:38:34264 // For kSafeFromGlobalPurgeDays in CookieStore.
jwwa9a0d482015-12-16 18:19:41265 FRIEND_TEST_ALL_PREFIXES(CookieMonsterStrictSecureTest, EvictSecureCookies);
jww82d99c12015-11-25 18:39:53266
jww31e32632015-12-16 23:38:34267 // For CookieDeleteEquivalent histogram enum.
268 FRIEND_TEST_ALL_PREFIXES(CookieMonsterTest,
269 CookieDeleteEquivalentHistogramTest);
270 FRIEND_TEST_ALL_PREFIXES(CookieMonsterStrictSecureTest,
271 CookieDeleteEquivalentHistogramTest);
272
[email protected]63ee33bd2012-03-15 09:29:58273 // Internal reasons for deletion, used to populate informative histograms
274 // and to provide a public cause for onCookieChange notifications.
275 //
276 // If you add or remove causes from this list, please be sure to also update
[email protected]7c4b66b2014-01-04 12:28:13277 // the CookieMonsterDelegate::ChangeCause mapping inside ChangeCauseMapping.
278 // Moreover, these are used as array indexes, so avoid reordering to keep the
[email protected]63ee33bd2012-03-15 09:29:58279 // histogram buckets consistent. New items (if necessary) should be added
280 // at the end of the list, just before DELETE_COOKIE_LAST_ENTRY.
281 enum DeletionCause {
282 DELETE_COOKIE_EXPLICIT = 0,
283 DELETE_COOKIE_OVERWRITE,
284 DELETE_COOKIE_EXPIRED,
285 DELETE_COOKIE_EVICTED,
286 DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE,
287 DELETE_COOKIE_DONT_RECORD, // e.g. For final cleanup after flush to store.
288 DELETE_COOKIE_EVICTED_DOMAIN,
289 DELETE_COOKIE_EVICTED_GLOBAL,
290
291 // Cookies evicted during domain level garbage collection that
292 // were accessed longer ago than kSafeFromGlobalPurgeDays
293 DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE,
294
295 // Cookies evicted during domain level garbage collection that
296 // were accessed more recently than kSafeFromGlobalPurgeDays
297 // (and thus would have been preserved by global garbage collection).
298 DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE,
299
300 // A common idiom is to remove a cookie by overwriting it with an
301 // already-expired expiration date. This captures that case.
302 DELETE_COOKIE_EXPIRED_OVERWRITE,
303
[email protected]6210ce52013-09-20 03:33:14304 // Cookies are not allowed to contain control characters in the name or
305 // value. However, we used to allow them, so we are now evicting any such
306 // cookies as we load them. See http://crbug.com/238041.
307 DELETE_COOKIE_CONTROL_CHAR,
308
jww82d99c12015-11-25 18:39:53309 // When strict secure cookies is enabled, non-secure cookies are evicted
310 // right after expired cookies.
311 DELETE_COOKIE_NON_SECURE,
312
[email protected]63ee33bd2012-03-15 09:29:58313 DELETE_COOKIE_LAST_ENTRY
314 };
315
mkwstc1aa4cc2015-04-03 19:57:45316 // This enum is used to generate a histogramed bitmask measureing the types
317 // of stored cookies. Please do not reorder the list when adding new entries.
318 // New items MUST be added at the end of the list, just before
319 // COOKIE_TYPE_LAST_ENTRY;
320 enum CookieType {
mkwst46549412016-02-01 10:05:37321 COOKIE_TYPE_SAME_SITE = 0,
mkwstc1aa4cc2015-04-03 19:57:45322 COOKIE_TYPE_HTTPONLY,
323 COOKIE_TYPE_SECURE,
324 COOKIE_TYPE_LAST_ENTRY
325 };
326
estark7feb65c2b2015-08-21 23:38:20327 // Used to populate a histogram containing information about the
328 // sources of Secure and non-Secure cookies: that is, whether such
329 // cookies are set by origins with cryptographic or non-cryptographic
330 // schemes. Please do not reorder the list when adding new
331 // entries. New items MUST be added at the end of the list, just
332 // before COOKIE_SOURCE_LAST_ENTRY.
333 //
334 // COOKIE_SOURCE_(NON)SECURE_COOKIE_(NON)CRYPTOGRAPHIC_SCHEME means
335 // that a cookie was set or overwritten from a URL with the given type
336 // of scheme. This enum should not be used when cookies are *cleared*,
337 // because its purpose is to understand if Chrome can deprecate the
338 // ability of HTTP urls to set/overwrite Secure cookies.
339 enum CookieSource {
340 COOKIE_SOURCE_SECURE_COOKIE_CRYPTOGRAPHIC_SCHEME = 0,
341 COOKIE_SOURCE_SECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
342 COOKIE_SOURCE_NONSECURE_COOKIE_CRYPTOGRAPHIC_SCHEME,
343 COOKIE_SOURCE_NONSECURE_COOKIE_NONCRYPTOGRAPHIC_SCHEME,
344 COOKIE_SOURCE_LAST_ENTRY
345 };
346
jww31e32632015-12-16 23:38:34347 // Used to populate a histogram for cookie setting in the "delete equivalent"
348 // step. Measures total attempts to delete an equivalent cookie as well as if
349 // a cookie is found to delete, if a cookie is skipped because it is secure,
350 // and if it is skipped for being secure but would have been deleted
351 // otherwise. The last two are only possible if strict secure cookies is
352 // turned on and if an insecure origin attempts to a set a cookie where a
353 // cookie with the same name and secure attribute already exists.
354 //
355 // Enum for UMA. Do no reorder or remove entries. New entries must be place
356 // directly before COOKIE_DELETE_EQUIVALENT_LAST_ENTRY and histograms.xml must
357 // be updated accordingly.
358 enum CookieDeleteEquivalent {
359 COOKIE_DELETE_EQUIVALENT_ATTEMPT = 0,
360 COOKIE_DELETE_EQUIVALENT_FOUND,
361 COOKIE_DELETE_EQUIVALENT_SKIPPING_SECURE,
362 COOKIE_DELETE_EQUIVALENT_WOULD_HAVE_DELETED,
363 COOKIE_DELETE_EQUIVALENT_LAST_ENTRY
364 };
365
erikchen1dd72a72015-05-06 20:45:05366 // The strategy for fetching cookies. Controlled by Finch experiment.
367 enum FetchStrategy {
368 // Fetches all cookies only when they're needed.
369 kFetchWhenNecessary = 0,
370 // Fetches all cookies as soon as any cookie is needed.
371 // This is the default behavior.
372 kAlwaysFetch,
373 // The fetch strategy is not yet determined.
374 kUnknownFetch,
375 };
376
[email protected]63ee33bd2012-03-15 09:29:58377 // The number of days since last access that cookies will not be subject
378 // to global garbage collection.
379 static const int kSafeFromGlobalPurgeDays;
380
381 // Record statistics every kRecordStatisticsIntervalSeconds of uptime.
382 static const int kRecordStatisticsIntervalSeconds = 10 * 60;
383
[email protected]63ee33bd2012-03-15 09:29:58384 // The following are synchronous calls to which the asynchronous methods
385 // delegate either immediately (if the store is loaded) or through a deferred
386 // task (if the store is not yet loaded).
387 bool SetCookieWithDetails(const GURL& url,
388 const std::string& name,
389 const std::string& value,
390 const std::string& domain,
391 const std::string& path,
mmenkefdd4fc72016-02-05 20:53:24392 base::Time creation_time,
393 base::Time expiration_time,
394 base::Time last_access_time,
[email protected]ab2d75c82013-04-19 18:39:04395 bool secure,
396 bool http_only,
mmenkeea4cd402016-02-02 04:03:10397 bool same_site,
jww601411a2015-11-20 19:46:57398 bool enforce_strict_secure,
[email protected]ab2d75c82013-04-19 18:39:04399 CookiePriority priority);
[email protected]63ee33bd2012-03-15 09:29:58400
401 CookieList GetAllCookies();
402
mkwstc611e6d2016-02-23 15:45:55403 CookieList GetCookieListWithOptions(const GURL& url,
404 const CookieOptions& options);
[email protected]63ee33bd2012-03-15 09:29:58405
[email protected]63ee33bd2012-03-15 09:29:58406 int DeleteAllCreatedBetween(const base::Time& delete_begin,
407 const base::Time& delete_end);
408
[email protected]d8428d52013-08-07 06:58:25409 int DeleteAllCreatedBetweenForHost(const base::Time delete_begin,
410 const base::Time delete_end,
411 const GURL& url);
[email protected]63ee33bd2012-03-15 09:29:58412
[email protected]63ee33bd2012-03-15 09:29:58413 bool SetCookieWithOptions(const GURL& url,
414 const std::string& cookie_line,
415 const CookieOptions& options);
416
417 std::string GetCookiesWithOptions(const GURL& url,
418 const CookieOptions& options);
419
[email protected]63ee33bd2012-03-15 09:29:58420 void DeleteCookie(const GURL& url, const std::string& cookie_name);
421
mmenke24379d52016-02-05 23:50:17422 int DeleteCanonicalCookie(const CanonicalCookie& cookie);
423
[email protected]63ee33bd2012-03-15 09:29:58424 bool SetCookieWithCreationTime(const GURL& url,
425 const std::string& cookie_line,
426 const base::Time& creation_time);
427
[email protected]264807b2012-04-25 14:49:37428 int DeleteSessionCookies();
429
erikchen1dd72a72015-05-06 20:45:05430 // The first access to the cookie store initializes it. This method should be
431 // called before any access to the cookie store.
432 void MarkCookieStoreAsInitialized();
[email protected]63ee33bd2012-03-15 09:29:58433
erikchen1dd72a72015-05-06 20:45:05434 // Fetches all cookies if the backing store exists and they're not already
435 // being fetched.
erikchen1dd72a72015-05-06 20:45:05436 void FetchAllCookiesIfNecessary();
437
438 // Fetches all cookies from the backing store.
erikchen1dd72a72015-05-06 20:45:05439 void FetchAllCookies();
440
441 // Whether all cookies should be fetched as soon as any is requested.
442 bool ShouldFetchAllCookiesWhenFetchingAnyCookie();
[email protected]63ee33bd2012-03-15 09:29:58443
444 // Stores cookies loaded from the backing store and invokes any deferred
445 // calls. |beginning_time| should be the moment PersistentCookieStore::Load
446 // was invoked and is used for reporting histogram_time_blocked_on_load_.
447 // See PersistentCookieStore::Load for details on the contents of cookies.
448 void OnLoaded(base::TimeTicks beginning_time,
449 const std::vector<CanonicalCookie*>& cookies);
450
451 // Stores cookies loaded from the backing store and invokes the deferred
452 // task(s) pending loading of cookies associated with the domain key
453 // (eTLD+1). Called when all cookies for the domain key(eTLD+1) have been
454 // loaded from DB. See PersistentCookieStore::Load for details on the contents
455 // of cookies.
mkwstbe84af312015-02-20 08:52:45456 void OnKeyLoaded(const std::string& key,
457 const std::vector<CanonicalCookie*>& cookies);
[email protected]63ee33bd2012-03-15 09:29:58458
459 // Stores the loaded cookies.
460 void StoreLoadedCookies(const std::vector<CanonicalCookie*>& cookies);
461
462 // Invokes deferred calls.
463 void InvokeQueue();
464
465 // Checks that |cookies_| matches our invariants, and tries to repair any
466 // inconsistencies. (In other words, it does not have duplicate cookies).
467 void EnsureCookiesMapIsValid();
468
469 // Checks for any duplicate cookies for CookieMap key |key| which lie between
470 // |begin| and |end|. If any are found, all but the most recent are deleted.
ellyjonescabf57422015-08-21 18:44:51471 void TrimDuplicateCookiesForKey(const std::string& key,
472 CookieMap::iterator begin,
473 CookieMap::iterator end);
[email protected]63ee33bd2012-03-15 09:29:58474
475 void SetDefaultCookieableSchemes();
476
477 void FindCookiesForHostAndDomain(const GURL& url,
478 const CookieOptions& options,
[email protected]63ee33bd2012-03-15 09:29:58479 std::vector<CanonicalCookie*>* cookies);
480
481 void FindCookiesForKey(const std::string& key,
482 const GURL& url,
483 const CookieOptions& options,
484 const base::Time& current,
[email protected]63ee33bd2012-03-15 09:29:58485 std::vector<CanonicalCookie*>* cookies);
486
487 // Delete any cookies that are equivalent to |ecc| (same path, domain, etc).
488 // If |skip_httponly| is true, httponly cookies will not be deleted. The
jww601411a2015-11-20 19:46:57489 // return value will be true if |skip_httponly| skipped an httponly cookie or
490 // |enforce_strict_secure| is true and the cookie to
491 // delete was Secure and the scheme of |ecc| is insecure. |key| is the key to
492 // find the cookie in cookies_; see the comment before the CookieMap typedef
493 // for details.
[email protected]63ee33bd2012-03-15 09:29:58494 // NOTE: There should never be more than a single matching equivalent cookie.
495 bool DeleteAnyEquivalentCookie(const std::string& key,
496 const CanonicalCookie& ecc,
497 bool skip_httponly,
jww601411a2015-11-20 19:46:57498 bool already_expired,
499 bool enforce_strict_secure);
[email protected]63ee33bd2012-03-15 09:29:58500
[email protected]6210ce52013-09-20 03:33:14501 // Takes ownership of *cc. Returns an iterator that points to the inserted
502 // cookie in cookies_. Guarantee: all iterators to cookies_ remain valid.
503 CookieMap::iterator InternalInsertCookie(const std::string& key,
504 CanonicalCookie* cc,
505 bool sync_to_store);
[email protected]63ee33bd2012-03-15 09:29:58506
507 // Helper function that sets cookies with more control.
508 // Not exposed as we don't want callers to have the ability
509 // to specify (potentially duplicate) creation times.
510 bool SetCookieWithCreationTimeAndOptions(const GURL& url,
511 const std::string& cookie_line,
512 const base::Time& creation_time,
513 const CookieOptions& options);
514
515 // Helper function that sets a canonical cookie, deleting equivalents and
516 // performing garbage collection.
mmenkeea4cd402016-02-02 04:03:10517 bool SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc,
[email protected]63ee33bd2012-03-15 09:29:58518 const CookieOptions& options);
519
drogerd5d1278c2015-03-17 19:21:51520 // Helper function calling SetCanonicalCookie() for all cookies in |list|.
521 bool SetCanonicalCookies(const CookieList& list);
522
[email protected]63ee33bd2012-03-15 09:29:58523 void InternalUpdateCookieAccessTime(CanonicalCookie* cc,
524 const base::Time& current_time);
525
526 // |deletion_cause| argument is used for collecting statistics and choosing
[email protected]7c4b66b2014-01-04 12:28:13527 // the correct CookieMonsterDelegate::ChangeCause for OnCookieChanged
528 // notifications. Guarantee: All iterators to cookies_ except to the
529 // deleted entry remain vaild.
mkwstbe84af312015-02-20 08:52:45530 void InternalDeleteCookie(CookieMap::iterator it,
531 bool sync_to_store,
[email protected]63ee33bd2012-03-15 09:29:58532 DeletionCause deletion_cause);
533
534 // If the number of cookies for CookieMap key |key|, or globally, are
535 // over the preset maximums above, garbage collect, first for the host and
536 // then globally. See comments above garbage collection threshold
537 // constants for details.
538 //
539 // Returns the number of cookies deleted (useful for debugging).
jww82d99c12015-11-25 18:39:53540 size_t GarbageCollect(const base::Time& current,
541 const std::string& key,
542 bool enforce_strict_secure);
[email protected]63ee33bd2012-03-15 09:29:58543
mkwste079ac412016-03-11 09:04:06544 // Helper for GarbageCollect(). Deletes up to |purge_goal| cookies with a
545 // priority less than or equal to |priority| from |cookies|, while ensuring
546 // that at least the |to_protect| most-recent cookies are retained.
547 //
548 // |cookies| must be sorted from least-recent to most-recent.
549 //
550 // |safe_date| is only used to determine the deletion cause for histograms.
551 //
552 // Returns the number of cookies deleted.
553 size_t PurgeLeastRecentMatches(CookieItVector* cookies,
554 CookiePriority priority,
555 size_t to_protect,
556 size_t purge_goal,
557 const base::Time& safe_date);
558
jww82d99c12015-11-25 18:39:53559 // Helper for GarbageCollect(); can be called directly as well. Deletes all
560 // expired cookies in |itpair|. If |cookie_its| is non-NULL, all the
561 // non-expired cookies from |itpair| are appended to |cookie_its|.
[email protected]63ee33bd2012-03-15 09:29:58562 //
563 // Returns the number of cookies deleted.
jww82d99c12015-11-25 18:39:53564 size_t GarbageCollectExpired(const base::Time& current,
565 const CookieMapItPair& itpair,
566 CookieItVector* cookie_its);
567
568 // Helper for GarbageCollect(). Deletes all cookies not marked Secure in
569 // |valid_cookies_its|. If |cookie_its| is non-NULL, all the Secure cookies
570 // from |itpair| are appended to |cookie_its|.
571 //
572 // Returns the numeber of cookies deleted.
573 size_t GarbageCollectNonSecure(const CookieItVector& valid_cookies,
574 CookieItVector* cookie_its);
[email protected]63ee33bd2012-03-15 09:29:58575
[email protected]8ad5d462013-05-02 08:45:26576 // Helper for GarbageCollect(). Deletes all cookies in the range specified by
577 // [|it_begin|, |it_end|). Returns the number of cookies deleted.
jww82d99c12015-11-25 18:39:53578 size_t GarbageCollectDeleteRange(const base::Time& current,
579 DeletionCause cause,
580 CookieItVector::iterator cookie_its_begin,
581 CookieItVector::iterator cookie_its_end);
582
583 // Helper for GarbageCollect(). Deletes cookies in |cookie_its| from least to
584 // most recently used, but only before |safe_date|. Also will stop deleting
585 // when the number of remaining cookies hits |purge_goal|.
586 size_t GarbageCollectLeastRecentlyAccessed(const base::Time& current,
587 const base::Time& safe_date,
588 size_t purge_goal,
589 CookieItVector cookie_its);
[email protected]63ee33bd2012-03-15 09:29:58590
davidben879199c2015-03-06 00:55:04591 // Find the key (for lookup in cookies_) based on the given domain.
592 // See comment on keys before the CookieMap typedef.
593 std::string GetKey(const std::string& domain) const;
594
[email protected]63ee33bd2012-03-15 09:29:58595 bool HasCookieableScheme(const GURL& url);
596
597 // Statistics support
598
599 // This function should be called repeatedly, and will record
600 // statistics if a sufficient time period has passed.
601 void RecordPeriodicStats(const base::Time& current_time);
602
603 // Initialize the above variables; should only be called from
604 // the constructor.
605 void InitializeHistograms();
606
607 // The resolution of our time isn't enough, so we do something
608 // ugly and increment when we've seen the same time twice.
609 base::Time CurrentTime();
610
611 // Runs the task if, or defers the task until, the full cookie database is
612 // loaded.
613 void DoCookieTask(const scoped_refptr<CookieMonsterTask>& task_item);
614
615 // Runs the task if, or defers the task until, the cookies for the given URL
616 // are loaded.
617 void DoCookieTaskForURL(const scoped_refptr<CookieMonsterTask>& task_item,
mkwstbe84af312015-02-20 08:52:45618 const GURL& url);
[email protected]63ee33bd2012-03-15 09:29:58619
drogerd5d1278c2015-03-17 19:21:51620 // Computes the difference between |old_cookies| and |new_cookies|, and writes
621 // the result in |cookies_to_add| and |cookies_to_delete|.
622 // This function has the side effect of changing the order of |old_cookies|
623 // and |new_cookies|. |cookies_to_add| and |cookies_to_delete| must be empty,
624 // and none of the arguments can be null.
625 void ComputeCookieDiff(CookieList* old_cookies,
626 CookieList* new_cookies,
627 CookieList* cookies_to_add,
628 CookieList* cookies_to_delete);
629
mmenkebe0910d2016-03-01 19:09:09630 // Runs the given callback. Used to avoid running callbacks after the store
631 // has been destroyed.
632 void RunCallback(const base::Closure& callback);
633
msarda0aad8f02014-10-30 09:22:39634 // Run all cookie changed callbacks that are monitoring |cookie|.
635 // |removed| is true if the cookie was deleted.
mmenkebe0910d2016-03-01 19:09:09636 void RunCookieChangedCallbacks(const CanonicalCookie& cookie, bool removed);
msarda0aad8f02014-10-30 09:22:39637
[email protected]63ee33bd2012-03-15 09:29:58638 // Histogram variables; see CookieMonster::InitializeHistograms() in
639 // cookie_monster.cc for details.
[email protected]de415552013-01-23 04:12:17640 base::HistogramBase* histogram_expiration_duration_minutes_;
[email protected]de415552013-01-23 04:12:17641 base::HistogramBase* histogram_evicted_last_access_minutes_;
642 base::HistogramBase* histogram_count_;
[email protected]de415552013-01-23 04:12:17643 base::HistogramBase* histogram_cookie_deletion_cause_;
mkwstc1aa4cc2015-04-03 19:57:45644 base::HistogramBase* histogram_cookie_type_;
estark7feb65c2b2015-08-21 23:38:20645 base::HistogramBase* histogram_cookie_source_scheme_;
jww31e32632015-12-16 23:38:34646 base::HistogramBase* histogram_cookie_delete_equivalent_;
[email protected]de415552013-01-23 04:12:17647 base::HistogramBase* histogram_time_blocked_on_load_;
[email protected]63ee33bd2012-03-15 09:29:58648
649 CookieMap cookies_;
650
erikchen1dd72a72015-05-06 20:45:05651 // Indicates whether the cookie store has been initialized.
[email protected]63ee33bd2012-03-15 09:29:58652 bool initialized_;
653
erikchen1dd72a72015-05-06 20:45:05654 // Indicates whether the cookie store has started fetching all cookies.
655 bool started_fetching_all_cookies_;
656 // Indicates whether the cookie store has finished fetching all cookies.
657 bool finished_fetching_all_cookies_;
658 // The strategy to use for fetching cookies.
659 FetchStrategy fetch_strategy_;
[email protected]63ee33bd2012-03-15 09:29:58660
661 // List of domain keys that have been loaded from the DB.
662 std::set<std::string> keys_loaded_;
663
664 // Map of domain keys to their associated task queues. These tasks are blocked
665 // until all cookies for the associated domain key eTLD+1 are loaded from the
666 // backend store.
mkwstbe84af312015-02-20 08:52:45667 std::map<std::string, std::deque<scoped_refptr<CookieMonsterTask>>>
[email protected]0184df32013-05-14 00:53:55668 tasks_pending_for_key_;
[email protected]63ee33bd2012-03-15 09:29:58669
670 // Queues tasks that are blocked until all cookies are loaded from the backend
671 // store.
mmenkef49fca0e2016-03-08 12:46:24672 std::deque<scoped_refptr<CookieMonsterTask>> tasks_pending_;
673
674 // Once a global cookie task has been seen, all per-key tasks must be put in
675 // |tasks_pending_| instead of |tasks_pending_for_key_| to ensure a reasonable
676 // view of the cookie store. This more to ensure fancy cookie export/import
677 // code has a consistent view of the CookieStore, rather than out of concern
678 // for typical use.
679 bool seen_global_task_;
[email protected]63ee33bd2012-03-15 09:29:58680
681 scoped_refptr<PersistentCookieStore> store_;
682
683 base::Time last_time_seen_;
684
685 // Minimum delay after updating a cookie's LastAccessDate before we will
686 // update it again.
687 const base::TimeDelta last_access_threshold_;
688
689 // Approximate date of access time of least recently accessed cookie
690 // in |cookies_|. Note that this is not guaranteed to be accurate, only a)
691 // to be before or equal to the actual time, and b) to be accurate
692 // immediately after a garbage collection that scans through all the cookies.
693 // This value is used to determine whether global garbage collection might
694 // find cookies to purge.
695 // Note: The default Time() constructor will create a value that compares
696 // earlier than any other time value, which is wanted. Thus this
697 // value is not initialized.
698 base::Time earliest_access_time_;
699
700 // During loading, holds the set of all loaded cookie creation times. Used to
701 // avoid ever letting cookies with duplicate creation times into the store;
702 // that way we don't have to worry about what sections of code are safe
703 // to call while it's in that state.
Avi Drissman13fc8932015-12-20 04:40:46704 std::set<int64_t> creation_times_;
[email protected]63ee33bd2012-03-15 09:29:58705
706 std::vector<std::string> cookieable_schemes_;
707
[email protected]7c4b66b2014-01-04 12:28:13708 scoped_refptr<CookieMonsterDelegate> delegate_;
[email protected]63ee33bd2012-03-15 09:29:58709
[email protected]63ee33bd2012-03-15 09:29:58710 base::Time last_statistic_record_time_;
711
[email protected]63ee33bd2012-03-15 09:29:58712 bool persist_session_cookies_;
713
ellyjones399e35a22014-10-27 11:09:56714 typedef std::map<std::pair<GURL, std::string>,
715 linked_ptr<CookieChangedCallbackList>> CookieChangedHookMap;
716 CookieChangedHookMap hook_map_;
717
mmenkebe0910d2016-03-01 19:09:09718 base::ThreadChecker thread_checker_;
719
720 base::WeakPtrFactory<CookieMonster> weak_ptr_factory_;
721
[email protected]63ee33bd2012-03-15 09:29:58722 DISALLOW_COPY_AND_ASSIGN(CookieMonster);
723};
724
[email protected]7c4b66b2014-01-04 12:28:13725class NET_EXPORT CookieMonsterDelegate
726 : public base::RefCountedThreadSafe<CookieMonsterDelegate> {
[email protected]63ee33bd2012-03-15 09:29:58727 public:
728 // The publicly relevant reasons a cookie might be changed.
729 enum ChangeCause {
730 // The cookie was changed directly by a consumer's action.
731 CHANGE_COOKIE_EXPLICIT,
732 // The cookie was automatically removed due to an insert operation that
733 // overwrote it.
734 CHANGE_COOKIE_OVERWRITE,
735 // The cookie was automatically removed as it expired.
736 CHANGE_COOKIE_EXPIRED,
737 // The cookie was automatically evicted during garbage collection.
738 CHANGE_COOKIE_EVICTED,
739 // The cookie was overwritten with an already-expired expiration date.
740 CHANGE_COOKIE_EXPIRED_OVERWRITE
741 };
742
743 // Will be called when a cookie is added or removed. The function is passed
744 // the respective |cookie| which was added to or removed from the cookies.
745 // If |removed| is true, the cookie was deleted, and |cause| will be set
[email protected]a2c92a1c2012-04-03 12:32:14746 // to the reason for its removal. If |removed| is false, the cookie was
[email protected]63ee33bd2012-03-15 09:29:58747 // added, and |cause| will be set to CHANGE_COOKIE_EXPLICIT.
748 //
749 // As a special case, note that updating a cookie's properties is implemented
750 // as a two step process: the cookie to be updated is first removed entirely,
751 // generating a notification with cause CHANGE_COOKIE_OVERWRITE. Afterwards,
752 // a new cookie is written with the updated values, generating a notification
753 // with cause CHANGE_COOKIE_EXPLICIT.
[email protected]5b9bc352012-07-18 13:13:34754 virtual void OnCookieChanged(const CanonicalCookie& cookie,
[email protected]63ee33bd2012-03-15 09:29:58755 bool removed,
756 ChangeCause cause) = 0;
757 protected:
[email protected]7c4b66b2014-01-04 12:28:13758 friend class base::RefCountedThreadSafe<CookieMonsterDelegate>;
759 virtual ~CookieMonsterDelegate() {}
[email protected]63ee33bd2012-03-15 09:29:58760};
761
[email protected]63ee33bd2012-03-15 09:29:58762typedef base::RefCountedThreadSafe<CookieMonster::PersistentCookieStore>
763 RefcountedPersistentCookieStore;
764
[email protected]c1b6e102013-04-10 20:54:49765class NET_EXPORT CookieMonster::PersistentCookieStore
[email protected]63ee33bd2012-03-15 09:29:58766 : public RefcountedPersistentCookieStore {
767 public:
[email protected]5b9bc352012-07-18 13:13:34768 typedef base::Callback<void(const std::vector<CanonicalCookie*>&)>
769 LoadedCallback;
[email protected]63ee33bd2012-03-15 09:29:58770
erikchen1dd72a72015-05-06 20:45:05771 // TODO(erikchen): Depending on the results of the cookie monster Finch
772 // experiment, update the name and description of this method. The behavior
773 // of this method doesn't change, but it has different semantics for the two
774 // different logic paths. See http://crbug.com/473483.
[email protected]63ee33bd2012-03-15 09:29:58775 // Initializes the store and retrieves the existing cookies. This will be
776 // called only once at startup. The callback will return all the cookies
777 // that are not yet returned to CookieMonster by previous priority loads.
mmenkebe0910d2016-03-01 19:09:09778 //
779 // |loaded_callback| may not be NULL.
[email protected]63ee33bd2012-03-15 09:29:58780 virtual void Load(const LoadedCallback& loaded_callback) = 0;
781
782 // Does a priority load of all cookies for the domain key (eTLD+1). The
783 // callback will return all the cookies that are not yet returned by previous
784 // loads, which includes cookies for the requested domain key if they are not
785 // already returned, plus all cookies that are chain-loaded and not yet
786 // returned to CookieMonster.
mmenkebe0910d2016-03-01 19:09:09787 //
788 // |loaded_callback| may not be NULL.
[email protected]63ee33bd2012-03-15 09:29:58789 virtual void LoadCookiesForKey(const std::string& key,
[email protected]dedec0b2013-02-28 04:50:10790 const LoadedCallback& loaded_callback) = 0;
[email protected]63ee33bd2012-03-15 09:29:58791
792 virtual void AddCookie(const CanonicalCookie& cc) = 0;
793 virtual void UpdateCookieAccessTime(const CanonicalCookie& cc) = 0;
794 virtual void DeleteCookie(const CanonicalCookie& cc) = 0;
795
[email protected]bf510ed2012-06-05 08:31:43796 // Instructs the store to not discard session only cookies on shutdown.
797 virtual void SetForceKeepSessionState() = 0;
[email protected]63ee33bd2012-03-15 09:29:58798
mmenkebe0910d2016-03-01 19:09:09799 // Flushes the store and posts |callback| when complete. |callback| may be
800 // NULL.
[email protected]63ee33bd2012-03-15 09:29:58801 virtual void Flush(const base::Closure& callback) = 0;
802
803 protected:
804 PersistentCookieStore() {}
[email protected]a9813302012-04-28 09:29:28805 virtual ~PersistentCookieStore() {}
[email protected]63ee33bd2012-03-15 09:29:58806
807 private:
[email protected]a9813302012-04-28 09:29:28808 friend class base::RefCountedThreadSafe<PersistentCookieStore>;
[email protected]63ee33bd2012-03-15 09:29:58809 DISALLOW_COPY_AND_ASSIGN(PersistentCookieStore);
810};
811
[email protected]63ee33bd2012-03-15 09:29:58812} // namespace net
813
814#endif // NET_COOKIES_COOKIE_MONSTER_H_